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 12 static void add_five(int* x) { 13 *x += 5; 14 } 15 16 SK_DECLARE_STATIC_ONCE(st_once); 17 DEF_TEST(SkOnce_Singlethreaded, r) { 18 int x = 0; 19 20 // No matter how many times we do this, x will be 5. 21 SkOnce(&st_once, add_five, &x); 22 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 27 REPORTER_ASSERT(r, 5 == x); 28 } 29 30 SK_DECLARE_STATIC_ONCE(mt_once); 31 DEF_TEST(SkOnce_Multithreaded, r) { 32 int x = 0; 33 // Run a bunch of tasks to be the first to add six to x. 34 SkTaskGroup().batch(1021, [&](int) { 35 void(*add_six)(int*) = [](int* p) { *p += 6; }; 36 SkOnce(&mt_once, add_six, &x); 37 }); 38 39 // Only one should have done the +=. 40 REPORTER_ASSERT(r, 6 == x); 41 } 42 43 static int gX = 0; 44 static void inc_gX() { gX++; } 45 46 SK_DECLARE_STATIC_ONCE(noarg_once); 47 DEF_TEST(SkOnce_NoArg, r) { 48 SkOnce(&noarg_once, inc_gX); 49 SkOnce(&noarg_once, inc_gX); 50 SkOnce(&noarg_once, inc_gX); 51 REPORTER_ASSERT(r, 1 == gX); 52 } 53