blob: 35c2015166b98e9209ad9cf8fbf4aa858d65815f [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"
reed89889b62014-10-29 12:36:45 -07009#include "SkRunnable.h"
mtklein406654b2014-09-03 15:34:37 -070010#include "SkTaskGroup.h"
mtklein@google.com3a19fb52013-10-09 16:12:23 +000011#include "Test.h"
mtklein@google.com3a19fb52013-10-09 16:12:23 +000012
commit-bot@chromium.org1f81fd62013-10-23 14:44:08 +000013static void add_five(int* x) {
mtklein@google.com3a19fb52013-10-09 16:12:23 +000014 *x += 5;
15}
16
mtklein199ba8e2015-01-13 08:40:23 -080017SK_DECLARE_STATIC_ONCE(st_once);
mtklein@google.com3a19fb52013-10-09 16:12:23 +000018DEF_TEST(SkOnce_Singlethreaded, r) {
19 int x = 0;
20
21 // No matter how many times we do this, x will be 5.
mtklein199ba8e2015-01-13 08:40:23 -080022 SkOnce(&st_once, add_five, &x);
23 SkOnce(&st_once, add_five, &x);
24 SkOnce(&st_once, add_five, &x);
25 SkOnce(&st_once, add_five, &x);
26 SkOnce(&st_once, add_five, &x);
mtklein@google.com3a19fb52013-10-09 16:12:23 +000027
28 REPORTER_ASSERT(r, 5 == x);
29}
30
mtklein199ba8e2015-01-13 08:40:23 -080031SK_DECLARE_STATIC_ONCE(mt_once);
mtklein@google.com3a19fb52013-10-09 16:12:23 +000032DEF_TEST(SkOnce_Multithreaded, r) {
mtklein@google.com3a19fb52013-10-09 16:12:23 +000033 int x = 0;
mtklein00b621c2015-06-17 15:26:15 -070034 // Run a bunch of tasks to be the first to add six to x.
35 sk_parallel_for(1021, [&](int) {
36 void(*add_six)(int*) = [](int* p) { *p += 6; };
37 SkOnce(&mt_once, add_six, &x);
38 });
mtklein@google.com3a19fb52013-10-09 16:12:23 +000039
40 // Only one should have done the +=.
41 REPORTER_ASSERT(r, 6 == x);
42}
commit-bot@chromium.org709ca752014-01-24 22:38:39 +000043
mtklein1b818772014-06-02 11:26:59 -070044static int gX = 0;
45static void inc_gX() { gX++; }
commit-bot@chromium.org709ca752014-01-24 22:38:39 +000046
mtklein199ba8e2015-01-13 08:40:23 -080047SK_DECLARE_STATIC_ONCE(noarg_once);
mtklein1b818772014-06-02 11:26:59 -070048DEF_TEST(SkOnce_NoArg, r) {
mtklein199ba8e2015-01-13 08:40:23 -080049 SkOnce(&noarg_once, inc_gX);
50 SkOnce(&noarg_once, inc_gX);
51 SkOnce(&noarg_once, inc_gX);
mtklein1b818772014-06-02 11:26:59 -070052 REPORTER_ASSERT(r, 1 == gX);
commit-bot@chromium.org709ca752014-01-24 22:38:39 +000053}