File tree Expand file tree Collapse file tree 2 files changed +26
-15
lines changed Expand file tree Collapse file tree 2 files changed +26
-15
lines changed Original file line number Diff line number Diff line change @@ -57,10 +57,10 @@ ThreadPool::ThreadPool(int num_threads) : running_(true) {
57
57
ThreadPool::~ThreadPool () {
58
58
{
59
59
// notify all threads to stop running
60
- std::lock_guard <std::mutex> l (mutex_);
60
+ std::unique_lock <std::mutex> l (mutex_);
61
61
running_ = false ;
62
- scheduled_.notify_all ();
63
62
}
63
+ scheduled_.notify_all ();
64
64
65
65
for (auto & t : threads_) {
66
66
t->join ();
@@ -70,19 +70,25 @@ ThreadPool::~ThreadPool() {
70
70
71
71
void ThreadPool::TaskLoop () {
72
72
while (true ) {
73
- std::unique_lock<std::mutex> lock (mutex_) ;
73
+ Task task ;
74
74
75
- scheduled_.wait (
76
- lock, [this ] { return !this ->tasks_ .empty () || !this ->running_ ; });
75
+ {
76
+ std::unique_lock<std::mutex> lock (mutex_);
77
+ scheduled_.wait (
78
+ lock, [this ] { return !this ->tasks_ .empty () || !this ->running_ ; });
77
79
78
- if (!running_ || tasks_.empty ()) {
79
- return ;
80
- }
80
+ if (!running_ && tasks_.empty ()) {
81
+ return ;
82
+ }
83
+
84
+ if (tasks_.empty ()) {
85
+ PADDLE_THROW (" This thread has no task to Run" );
86
+ }
81
87
82
- // pop a task from the task queue
83
- auto task = std::move (tasks_.front ());
84
- tasks_.pop ();
85
- lock. unlock ();
88
+ // pop a task from the task queue
89
+ task = std::move (tasks_.front ());
90
+ tasks_.pop ();
91
+ }
86
92
87
93
// run the task
88
94
task ();
Original file line number Diff line number Diff line change @@ -58,7 +58,7 @@ class ThreadPool {
58
58
~ThreadPool ();
59
59
60
60
// Run pushes a function to the task queue and returns a std::future
61
- // object. To wait for the completion of the task, call
61
+ // object. To wait for the completion of the task, call
62
62
// std::future::wait().
63
63
template <typename Callback>
64
64
std::future<void > Run (Callback fn) {
@@ -69,7 +69,6 @@ class ThreadPool {
69
69
template <typename Callback>
70
70
std::future<std::unique_ptr<platform::EnforceNotMet>> RunAndGetException (
71
71
Callback fn) {
72
- std::unique_lock<std::mutex> lock (mutex_);
73
72
Task task ([fn]() -> std::unique_ptr<platform::EnforceNotMet> {
74
73
try {
75
74
fn ();
@@ -84,7 +83,13 @@ class ThreadPool {
84
83
return nullptr ;
85
84
});
86
85
std::future<std::unique_ptr<platform::EnforceNotMet>> f = task.get_future ();
87
- tasks_.push (std::move (task));
86
+ {
87
+ std::unique_lock<std::mutex> lock (mutex_);
88
+ if (!running_) {
89
+ PADDLE_THROW (" enqueue on stopped ThreadPool" );
90
+ }
91
+ tasks_.push (std::move (task));
92
+ }
88
93
scheduled_.notify_one ();
89
94
return f;
90
95
}
You can’t perform that action at this time.
0 commit comments