天天看点

c++多线程——简单线程池

安全队列

#include <thread>
#include <iostream>
#include <atomic>
#include <functional>
#include <vector>
#include "tsafe_queue.h"
using namespace std;
class join_t {
    vector<thread>& threads;
public:
    explicit join_t(vector<thread>& 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<function<void()>> works; //工作队列
    vector<thread> threads;//线程池
    join_t joiner;//初始化类
    void worker_thread() {
        while (!done) {
            function<void()> 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<typename F_T>
    void submit(F_T f) {
        works.push(function<void()>(f));
    }
};
           

启动线程池以后,每个线程都在等待分配任务,都会去等待队列中取出任务。

简单测试一下。

int main()
{
    t_pool p;
    for (int i = 0; i < 1000; i++) {
        p.submit([i]() {
            cout << i * i<<endl;
            });
    }
    
    return 0;
}
           

继续阅读