Skip to content

Commit 8f6bfe6

Browse files
added exception guard on wait_for_all
1 parent 8cfaaed commit 8f6bfe6

3 files changed

Lines changed: 27 additions & 15 deletions

File tree

taskflow/threadpool/threadpool.hpp

Lines changed: 15 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -250,26 +250,28 @@ auto Threadpool::async(C&& c, Signal sig) {
250250
// After this method returns, all previously-scheduled tasks in the pool
251251
// will have been executed.
252252
inline void Threadpool::wait_for_all() {
253+
254+
if(is_worker()) {
255+
throw std::runtime_error("Worker thread cannot wait for all");
256+
}
253257

254258
std::mutex barrier_mutex;
255259
std::condition_variable barrier_cv;
256260
auto threads_to_sync{_threads.size()};
257261
std::vector<std::future<void>> futures;
258262

259-
auto barrier_task = [&] {
260-
std::unique_lock<std::mutex> lock(barrier_mutex);
261-
if (--threads_to_sync == 0) {
262-
barrier_cv.notify_all();
263-
}
264-
else {
265-
barrier_cv.wait(lock, [&threads_to_sync] {
266-
return threads_to_sync == 0;
267-
});
268-
}
269-
};
270-
271263
for(size_t i=0; i<_threads.size(); ++i) {
272-
futures.emplace_back(async(barrier_task));
264+
futures.emplace_back(async([&] () {
265+
std::unique_lock<std::mutex> lock(barrier_mutex);
266+
if (--threads_to_sync; threads_to_sync == 0) {
267+
barrier_cv.notify_all();
268+
}
269+
else {
270+
barrier_cv.wait(lock, [&threads_to_sync] {
271+
return threads_to_sync == 0;
272+
});
273+
}
274+
}));
273275
}
274276

275277
// Wait for all threads to have finished synchronization

taskflow/threadpool/threadpool_cxx14.hpp

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,9 @@
11
// A C++-14 based threadpool implementation inspired by Taskflow Threadpool.
2-
3-
// 2018/08/27 - contributed by Glen Fraser
2+
//
3+
// 2018/09/02 - contributed by Glen Fraser
4+
// - added wait_for_all method
45
//
6+
// 2018/08/27 - contributed by Glen Fraser
57
// taskflow.hpp was modified by Glen Fraser to produce this file
68
// (threadpool_cxx14.hpp), which is a "light" version of the library with
79
// restricted functionality -- it only exposes the tf::Threadpool class.
@@ -347,6 +349,10 @@ std::enable_if_t<
347349
// will have been executed.
348350
inline void Threadpool::wait_for_all() {
349351

352+
if(is_worker()) {
353+
throw std::runtime_error("Worker thread cannot wait for all");
354+
}
355+
350356
std::mutex barrier_mutex;
351357
std::condition_variable barrier_cv;
352358
auto threads_to_sync{_threads.size()};

unittest/threadpool_cxx14.cpp

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,8 @@
1+
// 2018/09/02 - contributed by Glen Fraser
2+
// - added wait_for_all test
3+
//
14
// 2018/08/28 - contributed by Glen Fraser
5+
// - added basic test
26

37
#define DOCTEST_CONFIG_IMPLEMENT_WITH_MAIN
48

0 commit comments

Comments
 (0)