1 /* 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 8 #include "SkAtomics.h" 9 #include "SkThreadUtils.h" 10 #include "SkTypes.h" 11 #include "Test.h" 12 13 struct AddInfo { 14 int32_t valueToAdd; 15 int timesToAdd; 16 }; 17 18 static int32_t base = 0; 19 20 static AddInfo gAdds[] = { 21 { 3, 100 }, 22 { 2, 200 }, 23 { 7, 150 }, 24 }; 25 26 static 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 33 DEF_TEST(Atomic, reporter) { 34 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]); 42 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)); 55 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 } 64 } 65