Skip to content

Commit

Permalink
Fixed wor canceled before done
Browse files Browse the repository at this point in the history
  • Loading branch information
COM8 committed Jan 26, 2025
1 parent ac9aa92 commit 46bf22f
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 7 deletions.
19 changes: 12 additions & 7 deletions cpr/threadpool2.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,7 @@ void ThreadPool2::addThread() {

void ThreadPool2::threadFunc(WorkerThread& workerThread) {
while (true) {
std::cv_status result{std::cv_status::timeout};
std::cv_status result{std::cv_status::no_timeout};
{
std::unique_lock lock(taskQueueMutex);
if (tasks.empty()) {
Expand All @@ -120,13 +120,18 @@ void ThreadPool2::threadFunc(WorkerThread& workerThread) {
}

// Check for tasks and execute one
const std::unique_lock lock(taskQueueMutex);
if (!tasks.empty()) {
idleThreadCount--;
const std::function<void()> task = std::move(tasks.front());
tasks.pop();
std::function<void()> task;
{
const std::unique_lock lock(taskQueueMutex);
if (!tasks.empty()) {
idleThreadCount--;
task = std::move(tasks.front());
tasks.pop();
}
}

// Execute the task
// Execute the task
if (task) {
task();
}
idleThreadCount++;
Expand Down
17 changes: 17 additions & 0 deletions test/threadpool2_tests.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,23 @@ TEST(ThreadPool2Tests, BasicWorkMultipleThreads) {
EXPECT_EQ(invCount, invCountExpected);
}

// Ensure only the current task gets finished when stopping worker
TEST(ThreadPool2Tests, CanceledBeforeDone) {
std::atomic_uint32_t invCount{0};
{
cpr::ThreadPool2 tp(1, 1);

for (size_t i = 0; i < 100; ++i) {
tp.Submit([&invCount]() -> void {
std::this_thread::sleep_for(std::chrono::seconds(1));
invCount++;
});
}
}

EXPECT_EQ(invCount, 1);
}

int main(int argc, char** argv) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
Expand Down

0 comments on commit 46bf22f

Please sign in to comment.