-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy paththread_pool.cpp
More file actions
34 lines (28 loc) · 879 Bytes
/
Copy paththread_pool.cpp
File metadata and controls
34 lines (28 loc) · 879 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#include "thread_pool.h"
#include <algorithm>
ThreadPool::ThreadPool(unsigned num_threads) {
if (num_threads == 0) num_threads = 1;
// Pre-size stats so each worker writes to its own slot (no reallocation, no
// sharing between workers => no data races on the stats vector).
stats_.resize(num_threads);
workers_.reserve(num_threads);
for (unsigned i = 0; i < num_threads; ++i) {
workers_.emplace_back([this, i] { worker_loop(i); });
}
}
ThreadPool::~ThreadPool() { close_and_join(); }
void ThreadPool::submit(const Chunk& chunk) { queue_.push(chunk); }
void ThreadPool::worker_loop(unsigned id) {
Chunk chunk;
while (queue_.pop(chunk)) {
process_chunk(chunk, stats_[id]);
}
}
void ThreadPool::close_and_join() {
if (joined_) return;
joined_ = true;
queue_.close();
for (std::thread& t : workers_) {
if (t.joinable()) t.join();
}
}