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 "SkOnce.h"
9#include "SkTaskGroup.h"
10#include "Test.h"
11
12static void add_five(int* x) {
13    *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.
20    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);
26
27    REPORTER_ASSERT(r, 5 == x);
28}
29
30DEF_TEST(SkOnce_Multithreaded, r) {
31    int x = 0;
32
33    // Run a bunch of tasks to be the first to add six to x.
34    SkOnce once;
35    SkTaskGroup().batch(1021, [&](int) {
36        once([&] { x += 6; });
37    });
38
39    // Only one should have done the +=.
40    REPORTER_ASSERT(r, 6 == x);
41}
42
43static int gX = 0;
44static void inc_gX() { gX++; }
45
46DEF_TEST(SkOnce_NoArg, r) {
47    SkOnce once;
48    once(inc_gX);
49    once(inc_gX);
50    once(inc_gX);
51    REPORTER_ASSERT(r, 1 == gX);
52}
53