|
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 |
6 | 18 | */
|
7 | 19 |
|
8 | 20 | #include <thread>
|
|
19 | 31 |
|
20 | 32 | namespace vtr {
|
21 | 33 |
|
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 |
| - * vtr::thread_pool pool(4); |
30 |
| - * pool.schedule_work([]{ |
31 |
| - * // Task body |
32 |
| - * }); |
33 |
| - * pool.wait_for_all(); // There's no API to wait for a single task |
34 |
| - */ |
35 | 34 | class thread_pool {
|
36 | 35 | private:
|
37 |
| - /* Thread-local data */ |
| 36 | + /** Thread-local data */ |
38 | 37 | struct ThreadData {
|
39 | 38 | std::thread thread;
|
40 |
| - /* Per-thread task queue */ |
| 39 | + /** Per-thread task queue */ |
41 | 40 | std::queue<std::function<void()>> task_queue;
|
42 | 41 |
|
43 |
| - /* Threads wait on cv for a stop signal or a new task |
| 42 | + /** Threads wait on cv for a stop signal or a new task |
44 | 43 | * queue_mutex is required for condition variable */
|
45 | 44 | std::mutex queue_mutex;
|
46 | 45 | std::condition_variable cv;
|
47 | 46 | bool stop = false;
|
48 | 47 | };
|
49 | 48 |
|
50 |
| - /* Container for thread-local data */ |
| 49 | + /** Container for thread-local data */ |
51 | 50 | std::vector<std::unique_ptr<ThreadData>> threads;
|
52 |
| - /* Used for round-robin scheduling */ |
| 51 | + /** Used for round-robin scheduling */ |
53 | 52 | std::atomic<size_t> next_thread{0};
|
54 |
| - /* Used for wait_for_all */ |
| 53 | + /** Used for wait_for_all */ |
55 | 54 | std::atomic<size_t> active_tasks{0};
|
56 | 55 |
|
57 |
| - /* Condition variable for wait_for_all */ |
| 56 | + /** Condition variable for wait_for_all */ |
58 | 57 | std::mutex completion_mutex;
|
59 | 58 | std::condition_variable completion_cv;
|
60 | 59 |
|
|
0 commit comments