blob: ef8d3d92251ead88dc5d046166665abbb3cc70ba [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"
mtklein406654b2014-09-03 15:34:37 -07009#include "SkTaskGroup.h"
mtklein@google.com3a19fb52013-10-09 16:12:23 +000010#include "Test.h"
mtklein@google.com3a19fb52013-10-09 16:12:23 +000011
commit-bot@chromium.org1f81fd62013-10-23 14:44:08 +000012static void add_five(int* x) {
mtklein@google.com3a19fb52013-10-09 16:12:23 +000013 *x += 5;
14}
15
16DEF_TEST(SkOnce_Singlethreaded, r) {
17 int x = 0;
18
19 // No matter how many times we do this, x will be 5.
mtkleind9dd4282016-04-18 08:09:11 -070020 SkOnce once;
21 once(add_five, &x);
22 once(add_five, &x);
23 once(add_five, &x);
24 once(add_five, &x);
25 once(add_five, &x);
mtklein@google.com3a19fb52013-10-09 16:12:23 +000026
27 REPORTER_ASSERT(r, 5 == x);
28}
29
mtklein@google.com3a19fb52013-10-09 16:12:23 +000030DEF_TEST(SkOnce_Multithreaded, r) {
mtklein@google.com3a19fb52013-10-09 16:12:23 +000031 int x = 0;
mtkleind9dd4282016-04-18 08:09:11 -070032
mtklein00b621c2015-06-17 15:26:15 -070033 // Run a bunch of tasks to be the first to add six to x.
mtkleind9dd4282016-04-18 08:09:11 -070034 SkOnce once;
mtklein279c7862016-01-04 19:13:19 -080035 SkTaskGroup().batch(1021, [&](int) {
mtkleind9dd4282016-04-18 08:09:11 -070036 once([&] { x += 6; });
mtklein00b621c2015-06-17 15:26:15 -070037 });
mtklein@google.com3a19fb52013-10-09 16:12:23 +000038
39 // Only one should have done the +=.
40 REPORTER_ASSERT(r, 6 == x);
41}
commit-bot@chromium.org709ca752014-01-24 22:38:39 +000042
mtklein1b818772014-06-02 11:26:59 -070043static int gX = 0;
44static void inc_gX() { gX++; }
commit-bot@chromium.org709ca752014-01-24 22:38:39 +000045
mtklein1b818772014-06-02 11:26:59 -070046DEF_TEST(SkOnce_NoArg, r) {
mtkleind9dd4282016-04-18 08:09:11 -070047 SkOnce once;
48 once(inc_gX);
49 once(inc_gX);
50 once(inc_gX);
mtklein1b818772014-06-02 11:26:59 -070051 REPORTER_ASSERT(r, 1 == gX);
commit-bot@chromium.org709ca752014-01-24 22:38:39 +000052}