Skip to content

Commit a6c8fca

Browse files
committed
Avoiding a deadlock scenario when submitting a task
1 parent 0e91979 commit a6c8fca

File tree

1 file changed

+14
-6
lines changed

1 file changed

+14
-6
lines changed

include/cpr/threadpool.h

Lines changed: 14 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -182,15 +182,23 @@ class ThreadPool {
182182
**/
183183
template <class Fn, class... Args>
184184
auto Submit(Fn&& fn, Args&&... args) {
185-
// Add a new worker thread in case the tasks queue is not empty and we still can add a thread
186185
{
187-
std::unique_lock lock(taskQueueMutex);
188-
if (idleThreadCount <= tasks.size() && curThreadCount < maxThreadCount) {
189-
const std::unique_lock lockControl(controlMutex);
190-
if (state == State::RUNNING) {
191-
addThread();
186+
const std::unique_lock lock(controlMutex);
187+
// Add a new worker thread in case the tasks queue is not empty and we still can add a thread
188+
bool shouldAddThread{false};
189+
{
190+
std::unique_lock lock(taskQueueMutex);
191+
if (idleThreadCount <= tasks.size() && curThreadCount < maxThreadCount) {
192+
if (state == State::RUNNING) {
193+
shouldAddThread = true;
194+
}
192195
}
193196
}
197+
198+
// We add a thread outside the 'taskQueueMutex' mutex block to avoid a potential deadlock caused within the 'addThread()' function.
199+
if (shouldAddThread) {
200+
addThread();
201+
}
194202
}
195203

196204
// Add task to queue

0 commit comments

Comments
 (0)