2013-10-09 16:12:23 +00:00
|
|
|
/*
|
|
|
|
* Copyright 2013 Google Inc.
|
|
|
|
*
|
|
|
|
* Use of this source code is governed by a BSD-style license that can be
|
|
|
|
* found in the LICENSE file.
|
|
|
|
*/
|
|
|
|
|
|
|
|
#include "SkOnce.h"
|
|
|
|
#include "SkThreadPool.h"
|
|
|
|
#include "Test.h"
|
|
|
|
#include "TestClassDef.h"
|
|
|
|
|
2013-10-23 14:44:08 +00:00
|
|
|
static void add_five(int* x) {
|
2013-10-09 16:12:23 +00:00
|
|
|
*x += 5;
|
|
|
|
}
|
|
|
|
|
|
|
|
DEF_TEST(SkOnce_Singlethreaded, r) {
|
|
|
|
int x = 0;
|
|
|
|
|
2013-10-23 14:44:08 +00:00
|
|
|
SK_DECLARE_STATIC_ONCE(once);
|
2013-10-09 16:12:23 +00:00
|
|
|
// No matter how many times we do this, x will be 5.
|
2013-10-23 14:44:08 +00:00
|
|
|
SkOnce(&once, add_five, &x);
|
|
|
|
SkOnce(&once, add_five, &x);
|
|
|
|
SkOnce(&once, add_five, &x);
|
|
|
|
SkOnce(&once, add_five, &x);
|
|
|
|
SkOnce(&once, add_five, &x);
|
2013-10-09 16:12:23 +00:00
|
|
|
|
|
|
|
REPORTER_ASSERT(r, 5 == x);
|
|
|
|
}
|
|
|
|
|
2013-12-05 19:20:49 +00:00
|
|
|
struct AddFour { void operator()(int* x) { *x += 4; } };
|
|
|
|
|
|
|
|
DEF_TEST(SkOnce_MiscFeatures, r) {
|
|
|
|
// Tests that we support functors and explicit SkOnceFlags.
|
|
|
|
int x = 0;
|
|
|
|
|
|
|
|
SkOnceFlag once = SK_ONCE_INIT;
|
|
|
|
SkOnce(&once, AddFour(), &x);
|
|
|
|
SkOnce(&once, AddFour(), &x);
|
|
|
|
SkOnce(&once, AddFour(), &x);
|
|
|
|
|
|
|
|
REPORTER_ASSERT(r, 4 == x);
|
|
|
|
}
|
|
|
|
|
2013-10-23 14:44:08 +00:00
|
|
|
static void add_six(int* x) {
|
2013-10-09 16:12:23 +00:00
|
|
|
*x += 6;
|
|
|
|
}
|
|
|
|
|
|
|
|
class Racer : public SkRunnable {
|
|
|
|
public:
|
2013-10-23 14:44:08 +00:00
|
|
|
SkOnceFlag* once;
|
2013-10-09 16:12:23 +00:00
|
|
|
int* ptr;
|
2013-10-23 14:44:08 +00:00
|
|
|
|
2013-10-09 16:12:23 +00:00
|
|
|
virtual void run() SK_OVERRIDE {
|
2013-10-23 14:44:08 +00:00
|
|
|
SkOnce(once, add_six, ptr);
|
2013-10-09 16:12:23 +00:00
|
|
|
}
|
|
|
|
};
|
|
|
|
|
|
|
|
DEF_TEST(SkOnce_Multithreaded, r) {
|
|
|
|
const int kTasks = 16, kThreads = 4;
|
|
|
|
|
|
|
|
// Make a bunch of tasks that will race to be the first to add six to x.
|
|
|
|
Racer racers[kTasks];
|
2013-10-23 14:44:08 +00:00
|
|
|
SK_DECLARE_STATIC_ONCE(once);
|
2013-10-09 16:12:23 +00:00
|
|
|
int x = 0;
|
|
|
|
for (int i = 0; i < kTasks; i++) {
|
2013-10-23 14:44:08 +00:00
|
|
|
racers[i].once = &once;
|
2013-10-09 16:12:23 +00:00
|
|
|
racers[i].ptr = &x;
|
|
|
|
}
|
|
|
|
|
|
|
|
// Let them race.
|
2013-10-10 18:49:04 +00:00
|
|
|
SkThreadPool pool(kThreads);
|
2013-10-09 16:12:23 +00:00
|
|
|
for (int i = 0; i < kTasks; i++) {
|
2013-10-10 18:49:04 +00:00
|
|
|
pool.add(&racers[i]);
|
2013-10-09 16:12:23 +00:00
|
|
|
}
|
2013-10-10 18:49:04 +00:00
|
|
|
pool.wait();
|
2013-10-09 16:12:23 +00:00
|
|
|
|
|
|
|
// Only one should have done the +=.
|
|
|
|
REPORTER_ASSERT(r, 6 == x);
|
|
|
|
}
|