Skip to content

Commit 1ac565d

Browse files
committed
Add a multithreaded test for ConcurrentReadableArray.
1 parent 9134e65 commit 1ac565d

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed

unittests/runtime/Concurrent.cpp

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,8 @@
1313
#include "swift/Runtime/Concurrent.h"
1414
#include "gtest/gtest.h"
1515

16+
#include "ThreadingHelpers.h"
17+
1618
using namespace swift;
1719

1820
TEST(ConcurrentReadableArrayTest, SingleThreaded) {
@@ -42,3 +44,48 @@ TEST(ConcurrentReadableArrayTest, SingleThreaded) {
4244
add(1000000);
4345
check();
4446
}
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

Comments
 (0)