Skip to content

Commit 46bf22f

Browse files
committed
Fixed wor canceled before done
1 parent ac9aa92 commit 46bf22f

File tree

2 files changed

+29
-7
lines changed

2 files changed

+29
-7
lines changed

cpr/threadpool2.cpp

Lines changed: 12 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -97,7 +97,7 @@ void ThreadPool2::addThread() {
9797

9898
void ThreadPool2::threadFunc(WorkerThread& workerThread) {
9999
while (true) {
100-
std::cv_status result{std::cv_status::timeout};
100+
std::cv_status result{std::cv_status::no_timeout};
101101
{
102102
std::unique_lock lock(taskQueueMutex);
103103
if (tasks.empty()) {
@@ -120,13 +120,18 @@ void ThreadPool2::threadFunc(WorkerThread& workerThread) {
120120
}
121121

122122
// Check for tasks and execute one
123-
const std::unique_lock lock(taskQueueMutex);
124-
if (!tasks.empty()) {
125-
idleThreadCount--;
126-
const std::function<void()> task = std::move(tasks.front());
127-
tasks.pop();
123+
std::function<void()> task;
124+
{
125+
const std::unique_lock lock(taskQueueMutex);
126+
if (!tasks.empty()) {
127+
idleThreadCount--;
128+
task = std::move(tasks.front());
129+
tasks.pop();
130+
}
131+
}
128132

129-
// Execute the task
133+
// Execute the task
134+
if (task) {
130135
task();
131136
}
132137
idleThreadCount++;

test/threadpool2_tests.cpp

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,23 @@ TEST(ThreadPool2Tests, BasicWorkMultipleThreads) {
4040
EXPECT_EQ(invCount, invCountExpected);
4141
}
4242

43+
// Ensure only the current task gets finished when stopping worker
44+
TEST(ThreadPool2Tests, CanceledBeforeDone) {
45+
std::atomic_uint32_t invCount{0};
46+
{
47+
cpr::ThreadPool2 tp(1, 1);
48+
49+
for (size_t i = 0; i < 100; ++i) {
50+
tp.Submit([&invCount]() -> void {
51+
std::this_thread::sleep_for(std::chrono::seconds(1));
52+
invCount++;
53+
});
54+
}
55+
}
56+
57+
EXPECT_EQ(invCount, 1);
58+
}
59+
4360
int main(int argc, char** argv) {
4461
::testing::InitGoogleTest(&argc, argv);
4562
return RUN_ALL_TESTS();

0 commit comments

Comments
 (0)