blob: 83ee66b6c8b41c42d08fe9b6ebae0f2e7bf64e41 [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
mtklein199ba8e2015-01-13 08:40:23 -080016SK_DECLARE_STATIC_ONCE(st_once);
mtklein@google.com3a19fb52013-10-09 16:12:23 +000017DEF_TEST(SkOnce_Singlethreaded, r) {
18 int x = 0;
19
20 // No matter how many times we do this, x will be 5.
mtklein199ba8e2015-01-13 08:40:23 -080021 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);
mtklein@google.com3a19fb52013-10-09 16:12:23 +000026
27 REPORTER_ASSERT(r, 5 == x);
28}
29
mtklein199ba8e2015-01-13 08:40:23 -080030SK_DECLARE_STATIC_ONCE(mt_once);
mtklein@google.com3a19fb52013-10-09 16:12:23 +000031DEF_TEST(SkOnce_Multithreaded, r) {
mtklein@google.com3a19fb52013-10-09 16:12:23 +000032 int x = 0;
mtklein00b621c2015-06-17 15:26:15 -070033 // Run a bunch of tasks to be the first to add six to x.
mtklein279c7862016-01-04 19:13:19 -080034 SkTaskGroup().batch(1021, [&](int) {
mtklein00b621c2015-06-17 15:26:15 -070035 void(*add_six)(int*) = [](int* p) { *p += 6; };
36 SkOnce(&mt_once, add_six, &x);
37 });
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
mtklein199ba8e2015-01-13 08:40:23 -080046SK_DECLARE_STATIC_ONCE(noarg_once);
mtklein1b818772014-06-02 11:26:59 -070047DEF_TEST(SkOnce_NoArg, r) {
mtklein199ba8e2015-01-13 08:40:23 -080048 SkOnce(&noarg_once, inc_gX);
49 SkOnce(&noarg_once, inc_gX);
50 SkOnce(&noarg_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}