天天看點

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;
}
           

繼續閱讀