Skip to content

Commit

Permalink
More reliable CanceledBeforeDone tests
Browse files Browse the repository at this point in the history
  • Loading branch information
COM8 committed Feb 9, 2025
1 parent 8d81b84 commit 212ea17
Showing 1 changed file with 24 additions and 8 deletions.
32 changes: 24 additions & 8 deletions test/threadpool_tests.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -117,20 +117,27 @@ TEST(ThreadPoolTests, StartStopBasicWorkMultipleThreads) {

// Ensure only the current task gets finished when stopping worker
TEST(ThreadPoolTests, CanceledBeforeDoneSingleThread) {
std::atomic_uint32_t invCount{0};
std::atomic_uint32_t threadsDone{0};
std::atomic_uint32_t threadsWaiting{0};
std::mutex lock;
lock.lock();

{
cpr::ThreadPool tp(1, 1);

for (size_t i = 0; i < 100; ++i) {
tp.Submit([&invCount, &lock]() -> void {
tp.Submit([&threadsDone, &lock, &threadsWaiting]() -> void {
threadsWaiting++;
const std::unique_lock guard(lock);
invCount++;
threadsDone++;
});
}

// Wait until all threads started. Can be replaced by std::barrier in C++20.
while (threadsWaiting < 1) {
std::this_thread::yield();
}

EXPECT_EQ(tp.GetCurThreadCount(), 1);
EXPECT_EQ(tp.GetIdleThreadCount(), 0);
EXPECT_EQ(tp.GetMaxThreadCount(), 1);
Expand All @@ -139,25 +146,34 @@ TEST(ThreadPoolTests, CanceledBeforeDoneSingleThread) {
lock.unlock();
}

EXPECT_EQ(invCount, 1);
EXPECT_EQ(threadsDone, 1);
}

// Ensure only the current task gets finished when stopping worker
TEST(ThreadPoolTests, CanceledBeforeDoneMultipleThreads) {
std::atomic_uint32_t invCount{0};
std::atomic_uint32_t threadsDone{0};
std::atomic_uint32_t threadsWaiting{0};
std::mutex lock;
lock.lock();

{
cpr::ThreadPool tp(1, 10);

for (size_t i = 0; i < 100; ++i) {
tp.Submit([&invCount, &lock]() -> void {
tp.Submit([&threadsDone, &lock, &threadsWaiting]() -> void {
threadsWaiting++;
const std::unique_lock guard(lock);
invCount++;
threadsDone++;
});
}

// Wait until all threads started. Can be replaced by std::barrier in C++20.
while (threadsWaiting < 10) {
std::this_thread::yield();
}

EXPECT_EQ(threadsDone, 0);

EXPECT_EQ(tp.GetCurThreadCount(), 10);
EXPECT_EQ(tp.GetIdleThreadCount(), 0);
EXPECT_EQ(tp.GetMaxThreadCount(), 10);
Expand All @@ -166,7 +182,7 @@ TEST(ThreadPoolTests, CanceledBeforeDoneMultipleThreads) {
lock.unlock();
}

EXPECT_EQ(invCount, 10);
EXPECT_EQ(threadsDone, 10);
}

int main(int argc, char** argv) {
Expand Down

0 comments on commit 212ea17

Please sign in to comment.