blob: 530fba79d55129d6f599b67156b9bf59549a100c [file] [log] [blame]
scroggo@google.com50ccb0a2012-07-16 16:51:28 +00001/*
2 * Copyright 2012 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
herb62a69c22015-09-29 11:47:45 -07008#include "SkAtomics.h"
scroggo@google.com50ccb0a2012-07-16 16:51:28 +00009#include "SkThreadUtils.h"
10#include "SkTypes.h"
tfarina@chromium.org8f6884a2014-01-24 20:56:26 +000011#include "Test.h"
scroggo@google.com50ccb0a2012-07-16 16:51:28 +000012
13struct AddInfo {
14 int32_t valueToAdd;
15 int timesToAdd;
scroggo@google.com50ccb0a2012-07-16 16:51:28 +000016};
17
18static int32_t base = 0;
19
20static AddInfo gAdds[] = {
mtkleina1bde7d2015-10-20 11:05:06 -070021 { 3, 100 },
22 { 2, 200 },
23 { 7, 150 },
scroggo@google.com50ccb0a2012-07-16 16:51:28 +000024};
25
26static void addABunchOfTimes(void* data) {
27 AddInfo* addInfo = static_cast<AddInfo*>(data);
28 for (int i = 0; i < addInfo->timesToAdd; i++) {
29 sk_atomic_add(&base, addInfo->valueToAdd);
30 }
31}
32
tfarina@chromium.orge4fafb12013-12-12 21:11:12 +000033DEF_TEST(Atomic, reporter) {
scroggo@google.com50ccb0a2012-07-16 16:51:28 +000034 int32_t total = base;
35 SkThread* threads[SK_ARRAY_COUNT(gAdds)];
36 for (size_t i = 0; i < SK_ARRAY_COUNT(gAdds); i++) {
37 total += gAdds[i].valueToAdd * gAdds[i].timesToAdd;
38 }
39 // Start the threads
40 for (size_t i = 0; i < SK_ARRAY_COUNT(gAdds); i++) {
41 threads[i] = new SkThread(addABunchOfTimes, &gAdds[i]);
scroggo@google.com50ccb0a2012-07-16 16:51:28 +000042 threads[i]->start();
43 }
44
45 // Now end the threads
46 for (size_t i = 0; i < SK_ARRAY_COUNT(gAdds); i++) {
47 threads[i]->join();
48 delete threads[i];
49 }
50 REPORTER_ASSERT(reporter, total == base);
51 // Ensure that the returned value from sk_atomic_add is correct.
52 int32_t valueToModify = 3;
53 const int32_t originalValue = valueToModify;
54 REPORTER_ASSERT(reporter, originalValue == sk_atomic_add(&valueToModify, 7));
herb08692672015-09-28 08:59:18 -070055
56 {
57 SkAtomic<int> v {0};
58 REPORTER_ASSERT(reporter, 0 == v.load());
59 v = 10;
60 REPORTER_ASSERT(reporter, 10 == v.load());
61 int q = v;
62 REPORTER_ASSERT(reporter, 10 == q);
63 }
scroggo@google.com50ccb0a2012-07-16 16:51:28 +000064}