OLD | NEW |
1 /* | 1 /* |
2 * Copyright 2013 Google Inc. | 2 * Copyright 2013 Google Inc. |
3 * | 3 * |
4 * Use of this source code is governed by a BSD-style license that can be | 4 * Use of this source code is governed by a BSD-style license that can be |
5 * found in the LICENSE file. | 5 * found in the LICENSE file. |
6 */ | 6 */ |
7 | 7 |
8 #include "SkOnce.h" | 8 #include "SkOnce.h" |
9 #include "SkThreadPool.h" | 9 #include "SkThreadPool.h" |
10 #include "Test.h" | 10 #include "Test.h" |
11 #include "TestClassDef.h" | 11 #include "TestClassDef.h" |
12 | 12 |
13 DEF_SK_ONCE(add_five, int* x) { | 13 DEF_SK_ONCE(add_five, int* x) { |
14 *x += 5; | 14 *x += 5; |
15 } | 15 } |
16 | 16 |
17 DEF_TEST(SkOnce_Singlethreaded, r) { | 17 DEF_TEST(SkOnce_Singlethreaded, r) { |
18 int x = 0; | 18 int x = 0; |
19 | 19 |
20 // No matter how many times we do this, x will be 5. | 20 // No matter how many times we do this, x will be 5. |
21 SK_ONCE(add_five, &x); | 21 SK_ONCE(add_five, &x); |
22 SK_ONCE(add_five, &x); | 22 SK_ONCE(add_five, &x); |
23 SK_ONCE(add_five, &x); | 23 SK_ONCE(add_five, &x); |
24 SK_ONCE(add_five, &x); | 24 SK_ONCE(add_five, &x); |
25 SK_ONCE(add_five, &x); | 25 SK_ONCE(add_five, &x); |
26 | 26 |
27 REPORTER_ASSERT(r, 5 == x); | 27 REPORTER_ASSERT(r, 5 == x); |
28 } | 28 } |
29 | 29 |
30 | |
31 DEF_SK_ONCE(add_six, int* x) { | 30 DEF_SK_ONCE(add_six, int* x) { |
32 *x += 6; | 31 *x += 6; |
33 } | 32 } |
34 | 33 |
35 namespace { | |
36 | |
37 class Racer : public SkRunnable { | 34 class Racer : public SkRunnable { |
38 public: | 35 public: |
39 int* ptr; | 36 int* ptr; |
40 virtual void run() SK_OVERRIDE { | 37 virtual void run() SK_OVERRIDE { |
41 SK_ONCE(add_six, ptr); | 38 SK_ONCE(add_six, ptr); |
42 } | 39 } |
43 }; | 40 }; |
44 | 41 |
45 } // namespace | |
46 | |
47 DEF_TEST(SkOnce_Multithreaded, r) { | 42 DEF_TEST(SkOnce_Multithreaded, r) { |
48 const int kTasks = 16, kThreads = 4; | 43 const int kTasks = 16, kThreads = 4; |
49 | 44 |
50 // Make a bunch of tasks that will race to be the first to add six to x. | 45 // Make a bunch of tasks that will race to be the first to add six to x. |
51 Racer racers[kTasks]; | 46 Racer racers[kTasks]; |
52 int x = 0; | 47 int x = 0; |
53 for (int i = 0; i < kTasks; i++) { | 48 for (int i = 0; i < kTasks; i++) { |
54 racers[i].ptr = &x; | 49 racers[i].ptr = &x; |
55 } | 50 } |
56 | 51 |
57 // Let them race. | 52 // Let them race. |
58 SkThreadPool pool(kThreads); | 53 SkThreadPool pool(kThreads); |
59 for (int i = 0; i < kTasks; i++) { | 54 for (int i = 0; i < kTasks; i++) { |
60 pool.add(&racers[i]); | 55 pool.add(&racers[i]); |
61 } | 56 } |
62 pool.wait(); | 57 pool.wait(); |
63 | 58 |
64 // Only one should have done the +=. | 59 // Only one should have done the +=. |
65 REPORTER_ASSERT(r, 6 == x); | 60 REPORTER_ASSERT(r, 6 == x); |
66 } | 61 } |
OLD | NEW |