xref: /aosp_15_r20/external/skia/tests/OnceTest.cpp (revision c8dee2aa9b3f27cf6c858bd81872bdeb2c07ed17)
1 /*
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 "include/private/base/SkOnce.h"
9 #include "src/core/SkTaskGroup.h"
10 #include "tests/Test.h"
11 
12 #include <functional>
13 
add_five(int * x)14 static void add_five(int* x) {
15     *x += 5;
16 }
17 
DEF_TEST(SkOnce_Singlethreaded,r)18 DEF_TEST(SkOnce_Singlethreaded, r) {
19     int x = 0;
20 
21     // No matter how many times we do this, x will be 5.
22     SkOnce once;
23     once(add_five, &x);
24     once(add_five, &x);
25     once(add_five, &x);
26     once(add_five, &x);
27     once(add_five, &x);
28 
29     REPORTER_ASSERT(r, 5 == x);
30 }
31 
DEF_TEST(SkOnce_Multithreaded,r)32 DEF_TEST(SkOnce_Multithreaded, r) {
33     int x = 0;
34 
35     // Run a bunch of tasks to be the first to add six to x.
36     SkOnce once;
37     SkTaskGroup().batch(1021, [&](int) {
38         once([&] { x += 6; });
39     });
40 
41     // Only one should have done the +=.
42     REPORTER_ASSERT(r, 6 == x);
43 }
44 
45 static int gX = 0;
inc_gX()46 static void inc_gX() { gX++; }
47 
DEF_TEST(SkOnce_NoArg,r)48 DEF_TEST(SkOnce_NoArg, r) {
49     SkOnce once;
50     once(inc_gX);
51     once(inc_gX);
52     once(inc_gX);
53     REPORTER_ASSERT(r, 1 == gX);
54 }
55