1. 程式人生 > >c++ 11 線程池的簡單封裝

c++ 11 線程池的簡單封裝

all div 線程池 not ont pri bre 簡單 ati

#include <condition_variable>
#include <queue>
#include <thread>
#include <vector>

class ThreadPool
{
public:
    ThreadPool(int threads = 4)
        : _stop(false)
    {
        for (int index = 0; index < threads; ++index)
        {
            _workers.emplace_back(std::thread(std::bind(
&ThreadPool::threadFunc, this))); } } void addTask(const std::function<void()> &task){ std::unique_lock<std::mutex> lk(_queueMutex); _taskQueue.emplace(task); _taskCondition.notify_one(); //喚醒一個線程 } ~ThreadPool() { { std::unique_lock
<std::mutex> lk(_queueMutex); _stop = true; _taskCondition.notify_all(); } for (auto&& worker : _workers) { worker.join(); } } static ThreadPool* getInstance() { static ThreadPool instance; return
&instance; } private: void threadFunc() { while (true) { std::function<void()> task = nullptr; { std::unique_lock<std::mutex> lk(_queueMutex); if (_stop) { break; } if (!_taskQueue.empty()) { task = std::move(_taskQueue.front()); _taskQueue.pop(); } else { _taskCondition.wait(lk); //掛起當前線程 continue; } } task(); } } std::vector<std::thread> _workers; std::queue< std::function<void()> > _taskQueue; std::mutex _queueMutex; std::condition_variable _taskCondition; bool _stop; };

調用方法:

ThreadPool::getInstance()->addTask([](){
 //do something in thread
});

c++ 11 線程池的簡單封裝