blob: 6c485a0f0ae35ba7e06be9aa3b376068a1ccaa7a [file] [log] [blame]
mtklein@google.com3a19fb52013-10-09 16:12:23 +00001/*
2 * Copyright 2013 Google Inc.
3 *
4 * Use of this source code is governed by a BSD-style license that can be
5 * found in the LICENSE file.
6 */
7
8#include "SkOnce.h"
mtklein@google.com3a19fb52013-10-09 16:12:23 +00009#include "SkThreadPool.h"
10#include "Test.h"
11#include "TestClassDef.h"
12
13DEF_SK_ONCE(add_five, int* x) {
14 *x += 5;
15}
16
17DEF_TEST(SkOnce_Singlethreaded, r) {
18 int x = 0;
19
20 // No matter how many times we do this, x will be 5.
21 SK_ONCE(add_five, &x);
22 SK_ONCE(add_five, &x);
23 SK_ONCE(add_five, &x);
24 SK_ONCE(add_five, &x);
25 SK_ONCE(add_five, &x);
26
27 REPORTER_ASSERT(r, 5 == x);
28}
29
mtklein@google.com3a19fb52013-10-09 16:12:23 +000030DEF_SK_ONCE(add_six, int* x) {
31 *x += 6;
32}
33
mtklein@google.com3a19fb52013-10-09 16:12:23 +000034class Racer : public SkRunnable {
35public:
36 int* ptr;
37 virtual void run() SK_OVERRIDE {
38 SK_ONCE(add_six, ptr);
39 }
40};
41
mtklein@google.com3a19fb52013-10-09 16:12:23 +000042DEF_TEST(SkOnce_Multithreaded, r) {
43 const int kTasks = 16, kThreads = 4;
44
45 // Make a bunch of tasks that will race to be the first to add six to x.
46 Racer racers[kTasks];
47 int x = 0;
48 for (int i = 0; i < kTasks; i++) {
49 racers[i].ptr = &x;
50 }
51
52 // Let them race.
commit-bot@chromium.orga7538ba2013-10-10 18:49:04 +000053 SkThreadPool pool(kThreads);
mtklein@google.com3a19fb52013-10-09 16:12:23 +000054 for (int i = 0; i < kTasks; i++) {
commit-bot@chromium.orga7538ba2013-10-10 18:49:04 +000055 pool.add(&racers[i]);
mtklein@google.com3a19fb52013-10-09 16:12:23 +000056 }
commit-bot@chromium.orga7538ba2013-10-10 18:49:04 +000057 pool.wait();
mtklein@google.com3a19fb52013-10-09 16:12:23 +000058
59 // Only one should have done the +=.
60 REPORTER_ASSERT(r, 6 == x);
61}