Skip to content

Commit fded2b4

Browse files
committed
More reliable CanceledBeforeDone tests
1 parent 33592c9 commit fded2b4

File tree

1 file changed

+24
-8
lines changed

1 file changed

+24
-8
lines changed

test/threadpool_tests.cpp

Lines changed: 24 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -117,20 +117,27 @@ TEST(ThreadPoolTests, StartStopBasicWorkMultipleThreads) {
117117

118118
// Ensure only the current task gets finished when stopping worker
119119
TEST(ThreadPoolTests, CanceledBeforeDoneSingleThread) {
120-
std::atomic_uint32_t invCount{0};
120+
std::atomic_uint32_t threadsDone{0};
121+
std::atomic_uint32_t threadsWaiting{0};
121122
std::mutex lock;
122123
lock.lock();
123124

124125
{
125126
cpr::ThreadPool tp(1, 1);
126127

127128
for (size_t i = 0; i < 100; ++i) {
128-
tp.Submit([&invCount, &lock]() -> void {
129+
tp.Submit([&threadsDone, &lock, &threadsWaiting]() -> void {
130+
threadsWaiting++;
129131
const std::unique_lock guard(lock);
130-
invCount++;
132+
threadsDone++;
131133
});
132134
}
133135

136+
// Wait until all threads started. Can be replaced by std::barrier in C++20.
137+
while (threadsWaiting < 1) {
138+
std::this_thread::yield();
139+
}
140+
134141
EXPECT_EQ(tp.GetCurThreadCount(), 1);
135142
EXPECT_EQ(tp.GetIdleThreadCount(), 0);
136143
EXPECT_EQ(tp.GetMaxThreadCount(), 1);
@@ -139,25 +146,34 @@ TEST(ThreadPoolTests, CanceledBeforeDoneSingleThread) {
139146
lock.unlock();
140147
}
141148

142-
EXPECT_EQ(invCount, 1);
149+
EXPECT_EQ(threadsDone, 1);
143150
}
144151

145152
// Ensure only the current task gets finished when stopping worker
146153
TEST(ThreadPoolTests, CanceledBeforeDoneMultipleThreads) {
147-
std::atomic_uint32_t invCount{0};
154+
std::atomic_uint32_t threadsDone{0};
155+
std::atomic_uint32_t threadsWaiting{0};
148156
std::mutex lock;
149157
lock.lock();
150158

151159
{
152160
cpr::ThreadPool tp(1, 10);
153161

154162
for (size_t i = 0; i < 100; ++i) {
155-
tp.Submit([&invCount, &lock]() -> void {
163+
tp.Submit([&threadsDone, &lock, &threadsWaiting]() -> void {
164+
threadsWaiting++;
156165
const std::unique_lock guard(lock);
157-
invCount++;
166+
threadsDone++;
158167
});
159168
}
160169

170+
// Wait until all threads started. Can be replaced by std::barrier in C++20.
171+
while (threadsWaiting < 10) {
172+
std::this_thread::yield();
173+
}
174+
175+
EXPECT_EQ(threadsDone, 0);
176+
161177
EXPECT_EQ(tp.GetCurThreadCount(), 10);
162178
EXPECT_EQ(tp.GetIdleThreadCount(), 0);
163179
EXPECT_EQ(tp.GetMaxThreadCount(), 10);
@@ -166,7 +182,7 @@ TEST(ThreadPoolTests, CanceledBeforeDoneMultipleThreads) {
166182
lock.unlock();
167183
}
168184

169-
EXPECT_EQ(invCount, 10);
185+
EXPECT_EQ(threadsDone, 10);
170186
}
171187

172188
int main(int argc, char** argv) {

0 commit comments

Comments
 (0)