这是一个线程池:
template<class T>
struct threaded_queue {
using lock = std::unique_lock<std::mutex>;
void push_back(T t) {
{
lock l(m);
data.push_back(std::move(t));
}
cv.notify_one();
}
boost::optional<T> pop_front() {
lock l(m);
cv.wait(l, [this]{ return abort || !data.empty(); });
if (abort) return {};
auto r = std::move(data.back());
data.pop_back();
return std::move(r);
}
void terminate() {
{
lock l(m);
abort = true;
data.clear();
}
cv.notify_all();
}
~threaded_queue()
{
terminate();
}
private:
std::mutex m;
std::deque<T> data;
std::condition_variable cv;
bool abort = false;
};
struct thread_pool {
thread_pool(std::size_t n = 1) { start_thread(n); }
thread_pool(thread_pool&&) = delete;
thread_pool& operator=(thread_pool&&) = delete;
~thread_pool() = default; // or `{ terminate(); }` if you want to abandon some tasks
template<class F, class R=std::result_of_t<F&()>>
std::future<R> queue_task(F task) {
std::packaged_task<R()> p(std::move(task));
auto r = p.get_future();
tasks.push_back(std::move(p));
return r;
}
template<class F, class R=std::result_of_t<F&()>>
std::future<R> run_task(F task) {
if (threads_active() >= total_threads()) {
start_thread();
}
return queue_task(std::move(task));
}
void terminate() {
tasks.terminate();
}
std::size_t threads_active() const {
return active;
}
std::size_t total_threads() const {
return threads.size();
}
void clear_threads() {
terminate();
threads.clear();
}
void start_thread(std::size_t n = 1) {
while(n-->0) {
threads.push_back(
std::async(std::launch::async,
[this]{
while(auto task = tasks.pop_front()) {
++active;
try{
(*task)();
} catch(...) {
--active;
throw;
}
--active;
}
}
)
);
}
}
private:
std::vector<std::future<void>> threads;
threaded_queue<std::packaged_task<void()>> tasks;
std::atomic<std::size_t> active;
};
你给它多线程或者在建或通过start_thread
如何。
然后您queue_task
。这会返回一个std::future
,告诉你任务何时完成。
随着线程完成任务,他们去threaded_queue
并寻找更多。
当threaded_queue
被销毁时,它会中止其中的所有数据。
当thread_pool
被销毁时,它会中止所有将来的任务,然后等待所有未完成的任务完成。
Live example。
为了记录,总结一个'vector'是通过工作者线程协调任务的一个可怕情况,这些线程急切地从一组共同的值中抽取出来;要做的工作量很小,同步的成本只能确保一次计算的每个值都很高。预先对数据进行分区更有意义,因为它消除了对同步的需求(除了在结合其结果之前等待所有线程完成),并且可以预测每个线程的数据访问模式(适用于任何内存系统预取启发式)。 – ShadowRanger