@@ -26,39 +26,42 @@ namespace vtr {
26
26
*
27
27
* Example usage:
28
28
*
29
- * vtr::thread_pool pool(4);
29
+ * ```
30
+ * vtr::thread_pool pool(4); // 4 threads
30
31
* pool.schedule_work([]{
31
32
* // Task body
32
33
* });
33
- * pool.wait_for_all(); // There's no API to wait for a single task
34
+ * pool.wait_for_all(); // There's no API to wait for a single task
35
+ * ```
34
36
*/
35
37
class thread_pool {
36
38
private:
37
- /* Thread-local data */
39
+ /* * Thread-local data */
38
40
struct ThreadData {
39
41
std::thread thread;
40
- /* Per-thread task queue */
42
+ /* * Per-thread task queue */
41
43
std::queue<std::function<void ()>> task_queue;
42
44
43
- /* Threads wait on cv for a stop signal or a new task
45
+ /* * Threads wait on cv for a stop signal or a new task
44
46
* queue_mutex is required for condition variable */
45
47
std::mutex queue_mutex;
46
48
std::condition_variable cv;
47
49
bool stop = false ;
48
50
};
49
51
50
- /* Container for thread-local data */
52
+ /* * Container for thread-local data */
51
53
std::vector<std::unique_ptr<ThreadData>> threads;
52
- /* Used for round-robin scheduling */
54
+ /* * Used for round-robin scheduling */
53
55
std::atomic<size_t > next_thread{0 };
54
- /* Used for wait_for_all */
56
+ /* * Used for wait_for_all */
55
57
std::atomic<size_t > active_tasks{0 };
56
58
57
- /* Condition variable for wait_for_all */
59
+ /* * Condition variable for wait_for_all */
58
60
std::mutex completion_mutex;
59
61
std::condition_variable completion_cv;
60
62
61
63
public:
64
+ /* * Create a thread pool with \p thread_count threads. */
62
65
thread_pool (size_t thread_count) {
63
66
threads.reserve (thread_count);
64
67
@@ -96,6 +99,7 @@ class thread_pool {
96
99
}
97
100
}
98
101
102
+ /* * Schedule a function to be executed on one of the threads. */
99
103
template <typename F>
100
104
void schedule_work (F&& f) {
101
105
active_tasks++;
@@ -133,6 +137,8 @@ class thread_pool {
133
137
thread_data->cv .notify_one ();
134
138
}
135
139
140
+ /* * Wait until the work queue is empty.
141
+ * Note that functions are allowed to schedule new functions. */
136
142
void wait_for_all () {
137
143
std::unique_lock<std::mutex> lock (completion_mutex);
138
144
completion_cv.wait (lock, [this ]() { return active_tasks == 0 ; });
0 commit comments