File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change @@ -53,6 +53,8 @@ namespace dp {
5353 auto &task = queues_[id].tasks .front ();
5454 // invoke the task
5555 std::invoke (std::move (task));
56+ // decrement in-flight counter
57+ --in_flight_;
5658 // remove task from the queue
5759 queues_[id].tasks .pop ();
5860 }
@@ -62,6 +64,11 @@ namespace dp {
6264 }
6365
6466 ~thread_pool () {
67+ // wait for tasks to complete first
68+ do {
69+ std::this_thread::yield ();
70+ } while (in_flight_ > 0 );
71+
6572 // stop all threads
6673 for (std::size_t i = 0 ; i < threads_.size (); ++i) {
6774 threads_[i].request_stop ();
@@ -131,13 +138,15 @@ namespace dp {
131138 template <typename Function>
132139 void enqueue_task (Function &&f) {
133140 const std::size_t i = count_++ % queues_.size ();
141+ ++in_flight_;
134142 queues_[i].tasks .push (std::forward<Function>(f));
135143 queues_[i].semaphore .release ();
136144 }
137145
138146 std::vector<std::jthread> threads_;
139147 std::deque<task_queue> queues_;
140148 std::size_t count_ = 0 ;
149+ std::atomic<int64_t > in_flight_{0 };
141150 };
142151
143152 /* *
You can’t perform that action at this time.
0 commit comments