|
13 | 13 | #include "swift/Runtime/Concurrent.h"
|
14 | 14 | #include "gtest/gtest.h"
|
15 | 15 |
|
| 16 | +#include "ThreadingHelpers.h" |
| 17 | + |
16 | 18 | using namespace swift;
|
17 | 19 |
|
18 | 20 | TEST(ConcurrentReadableArrayTest, SingleThreaded) {
|
@@ -42,3 +44,48 @@ TEST(ConcurrentReadableArrayTest, SingleThreaded) {
|
42 | 44 | add(1000000);
|
43 | 45 | check();
|
44 | 46 | }
|
| 47 | + |
| 48 | +TEST(ConcurrentReadableArrayTest, MultiThreaded) { |
| 49 | + const int writerCount = 16; |
| 50 | + const int readerCount = 8; |
| 51 | + const int insertCount = 100000; |
| 52 | + |
| 53 | + struct Value { |
| 54 | + int threadNumber; |
| 55 | + int x; |
| 56 | + }; |
| 57 | + ConcurrentReadableArray<Value> array; |
| 58 | + |
| 59 | + auto writer = [&](int threadNumber) { |
| 60 | + for (int i = 0; i < insertCount; i++) |
| 61 | + array.push_back({ threadNumber, i }); |
| 62 | + }; |
| 63 | + |
| 64 | + auto reader = [&] { |
| 65 | + int maxByThread[writerCount]; |
| 66 | + bool done = false; |
| 67 | + while (!done) { |
| 68 | + for (int i = 0; i < writerCount; i++) |
| 69 | + maxByThread[i] = -1; |
| 70 | + for (auto element : array.snapshot()) { |
| 71 | + ASSERT_LT(element.threadNumber, writerCount); |
| 72 | + ASSERT_GT(element.x, maxByThread[element.threadNumber]); |
| 73 | + maxByThread[element.threadNumber] = element.x; |
| 74 | + } |
| 75 | + done = true; |
| 76 | + for (int i = 0; i < writerCount; i++) { |
| 77 | + if (maxByThread[i] < insertCount - 1) |
| 78 | + done = false; |
| 79 | + } |
| 80 | + } |
| 81 | + }; |
| 82 | + |
| 83 | + threadedExecute(writerCount + readerCount, [&](int i) { |
| 84 | + if (i < writerCount) |
| 85 | + writer(i); |
| 86 | + else |
| 87 | + reader(); |
| 88 | + }); |
| 89 | + |
| 90 | + ASSERT_EQ(array.snapshot().count(), writerCount * insertCount); |
| 91 | +} |
0 commit comments