|
3 | 3 | /**
|
4 | 4 | * @file vtr_thread_pool.h
|
5 | 5 | * @brief A generic thread pool for parallel task execution
|
6 |
| - * |
7 |
| - * A thread pool for parallel task execution. It is a naive |
8 |
| - * implementation which uses a queue for each thread and assigns |
9 |
| - * tasks in a round robin fashion. |
10 |
| - * |
11 |
| - * Example usage: |
12 |
| - * |
13 |
| - * vtr::thread_pool pool(4); |
14 |
| - * pool.schedule_work([]{ |
15 |
| - * // Task body |
16 |
| - * }); |
17 |
| - * pool.wait_for_all(); // There's no API to wait for a single task |
18 | 6 | */
|
19 | 7 |
|
20 | 8 | #include <thread>
|
|
31 | 19 |
|
32 | 20 | namespace vtr {
|
33 | 21 |
|
| 22 | +/** |
| 23 | + * A thread pool for parallel task execution. It is a naive |
| 24 | + * implementation which uses a queue for each thread and assigns |
| 25 | + * tasks in a round robin fashion. |
| 26 | + * |
| 27 | + * Example usage: |
| 28 | + * |
| 29 | + * ``` |
| 30 | + * vtr::thread_pool pool(4); // 4 threads |
| 31 | + * pool.schedule_work([]{ |
| 32 | + * // Task body |
| 33 | + * }); |
| 34 | + * pool.wait_for_all(); // There's no API to wait for a single task |
| 35 | + * ``` |
| 36 | + */ |
34 | 37 | class thread_pool {
|
35 | 38 | private:
|
36 | 39 | /** Thread-local data */
|
@@ -58,6 +61,7 @@ class thread_pool {
|
58 | 61 | std::condition_variable completion_cv;
|
59 | 62 |
|
60 | 63 | public:
|
| 64 | + /** Create a thread pool with \p thread_count threads. */ |
61 | 65 | thread_pool(size_t thread_count) {
|
62 | 66 | threads.reserve(thread_count);
|
63 | 67 |
|
@@ -95,6 +99,7 @@ class thread_pool {
|
95 | 99 | }
|
96 | 100 | }
|
97 | 101 |
|
| 102 | + /** Schedule a function to be executed on one of the threads. */ |
98 | 103 | template<typename F>
|
99 | 104 | void schedule_work(F&& f) {
|
100 | 105 | active_tasks++;
|
@@ -132,6 +137,8 @@ class thread_pool {
|
132 | 137 | thread_data->cv.notify_one();
|
133 | 138 | }
|
134 | 139 |
|
| 140 | + /** Wait until the work queue is empty. |
| 141 | + * Note that functions are allowed to schedule new functions. */ |
135 | 142 | void wait_for_all() {
|
136 | 143 | std::unique_lock<std::mutex> lock(completion_mutex);
|
137 | 144 | completion_cv.wait(lock, [this]() { return active_tasks == 0; });
|
|
0 commit comments