Skip to content

Commit 588b59c

Browse files
committed
Check stop condition under lock. Use emplace instead of push.
1 parent 20061c5 commit 588b59c

File tree

1 file changed

+6
-5
lines changed

1 file changed

+6
-5
lines changed

ThreadPool.h

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -60,10 +60,6 @@ auto ThreadPool::enqueue(F&& f, Args&&... args)
6060
-> std::future<typename std::result_of<F(Args...)>::type>
6161
{
6262
typedef typename std::result_of<F(Args...)>::type return_type;
63-
64-
// don't allow enqueueing after stopping the pool
65-
if(stop)
66-
throw std::runtime_error("enqueue on stopped ThreadPool");
6763

6864
auto task = std::make_shared< std::packaged_task<return_type()> >(
6965
std::bind(std::forward<F>(f), std::forward<Args>(args)...)
@@ -72,7 +68,12 @@ auto ThreadPool::enqueue(F&& f, Args&&... args)
7268
std::future<return_type> res = task->get_future();
7369
{
7470
std::unique_lock<std::mutex> lock(queue_mutex);
75-
tasks.push([task](){ (*task)(); });
71+
72+
// don't allow enqueueing after stopping the pool
73+
if(stop)
74+
throw std::runtime_error("enqueue on stopped ThreadPool");
75+
76+
tasks.emplace([task](){ (*task)(); });
7677
}
7778
condition.notify_one();
7879
return res;

0 commit comments

Comments
 (0)