Skip to content

Commit e19dfa1

Browse files
committed
chore(thread_pool): refine code
1 parent 11e3c42 commit e19dfa1

File tree

1 file changed

+14
-11
lines changed

1 file changed

+14
-11
lines changed

thread/ThreadPool.h

Lines changed: 14 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -38,18 +38,21 @@ class ThreadPool : boost::noncopyable
3838
template<typename Func, typename... Args>
3939
inline auto run_future(Func&& func, Args&&... args) -> std::future<typename std::result_of<Func(Args...)>::type>
4040
{
41-
if (threads_.empty()) {
42-
func(args...);
41+
if (threads_.empty()) {
42+
func(args...);
43+
}
44+
using ret_type = typename std::result_of<Func(Args...)>::type;
45+
auto task = std::make_shared<std::packaged_task<ret_type()>>(std::bind(std::forward<Func>(func), std::forward<Args>(args)...));
46+
auto ret = task->get_future();
47+
do {
48+
MutexLockGuard lock(mutex_);
49+
if (!running_) {
50+
throw std::runtime_error("enqueue on stopped ThreadPool");
4351
}
44-
using ret_type = typename std::result_of<Func(Args...)>::type;
45-
auto task = std::make_shared<std::packaged_task<ret_type()>>(std::bind(std::forward<Func>(func), std::forward<Args>(args)...));
46-
auto ret = task->get_future();
47-
do {
48-
MutexLockGuard lock(mutex_);
49-
queue_.push_back([task]() { (*task)(); });
50-
cond_.notify();
51-
} while (0);
52-
return std::move(ret);
52+
queue_.push_back([task]() { (*task)(); });
53+
cond_.notify();
54+
} while (0);
55+
return std::move(ret);
5356
}
5457

5558
private:

0 commit comments

Comments
 (0)