安全队列
#include#include #include #include #include #include "tsafe_queue.h" using namespace std; class join_t { vector & threads; public: explicit join_t(vector & ts):threads(ts) {} ~join_t() { for (int i = 0; i < threads.size(); i++) { if (threads[i].joinable()) threads[i].join(); } } }; class t_pool { atomic_bool done; tsafe_queue > works; //工作队列 vector threads;//线程池 join_t joiner;//初始化类 void worker_thread() { while (!done) { function task; if (works.try_pop(task)) { task(); } else { this_thread::yield();//没有任务时,让出时间片 } } } public: t_pool() :done(false), joiner(threads) { unsigned const max_t = thread::hardware_concurrency() - 2; try {//创建同样数量的线程 for (unsigned i = 0; i < max_t; i++) { threads.push_back( std::thread(&t_pool::worker_thread, this)); } } catch (...) { done = true; throw; } } ~t_pool() { done = false; } template void submit(F_T f) { works.push(function (f)); } };
启动线程池以后,每个线程都在等待分配任务,都会去等待队列中取出任务。
简单测试一下。
int main()
{
t_pool p;
for (int i = 0; i < 1000; i++) {
p.submit([i]() {
cout << i * i<


