Skip to content

Commit

Permalink
Avoiding a deadlock scenario when submitting a task
Browse files Browse the repository at this point in the history
  • Loading branch information
COM8 committed Feb 14, 2025
1 parent 0e91979 commit a6c8fca
Showing 1 changed file with 14 additions and 6 deletions.
20 changes: 14 additions & 6 deletions include/cpr/threadpool.h
Original file line number Diff line number Diff line change
Expand Up @@ -182,15 +182,23 @@ class ThreadPool {
**/
template <class Fn, class... Args>
auto Submit(Fn&& fn, Args&&... args) {
// Add a new worker thread in case the tasks queue is not empty and we still can add a thread
{
std::unique_lock lock(taskQueueMutex);
if (idleThreadCount <= tasks.size() && curThreadCount < maxThreadCount) {
const std::unique_lock lockControl(controlMutex);
if (state == State::RUNNING) {
addThread();
const std::unique_lock lock(controlMutex);
// Add a new worker thread in case the tasks queue is not empty and we still can add a thread
bool shouldAddThread{false};
{
std::unique_lock lock(taskQueueMutex);
if (idleThreadCount <= tasks.size() && curThreadCount < maxThreadCount) {
if (state == State::RUNNING) {
shouldAddThread = true;
}
}
}

// We add a thread outside the 'taskQueueMutex' mutex block to avoid a potential deadlock caused within the 'addThread()' function.
if (shouldAddThread) {
addThread();
}
}

// Add task to queue
Expand Down

0 comments on commit a6c8fca

Please sign in to comment.