本文主要介紹如何設計一個高效通用的執行緒池,詳細說明了一個執行緒池由哪幾部分組成,最后通過100行C++代碼實作一個高效通用的執行緒池,
1. 執行緒池的基礎元素
- std::vector<std::thread> workers
- std::queue<std::function<void()>> tasks
- std::mutex queue_mutex
- std::condition_variable condition
- bool stop
2. 基礎元素的說明
- workers:執行緒容器,用于從tasks佇列中獲取任務,并執行該任務
- tasks:任務佇列,用于存盤添加到執行緒池中的待執行任務
- queue_mutex:讀寫任務佇列時的互斥鎖,tasks佇列是一個競爭資源,對tasks佇列進行操作時需要保證互斥性
- condition:條件變數,用來監視資源是否可用(監視任務佇列是否有任務和stop是否為true)
- stop:全域控制變數,用來控制是否可以往tasks佇列中添加任務和佇列為空時,執行緒池中的執行緒是否可以退出
3. condition的補充說明
- 當 std::condition_variable 物件的某個 wait 函式被呼叫的時候,它使用 std::unique_lock(通過 std::mutex 定義的) 來鎖住當前執行緒,當前執行緒會一直被阻塞,直到另外一個執行緒在相同的 std::condition_variable 物件上呼叫了notify_one/notify_all 函式來喚醒當前執行緒
- 對于wait函式的pred引數,只有當 pred 條件為 false 時呼叫 wait() 才會阻塞當前執行緒,并且在收到其他執行緒的通知后只有當 pred 為 true 時才會被解除阻塞
4. C++實作
#ifndef THREAD_POOL_H
#define THREAD_POOL_H
#include <vector>
#include <queue>
#include <memory>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <future>
#include <functional>
#include <stdexcept>
class ThreadPool {
public:
ThreadPool(size_t);
template<class F, class... Args>
auto enqueue(F&& f, Args&&... args)
-> std::future<typename std::result_of<F(Args...)>::type>;
~ThreadPool();
private:
// need to keep track of threads so we can join them
std::vector< std::thread > workers;
// the task queue
std::queue< std::function<void()> > tasks;
// synchronization
std::mutex queue_mutex;
std::condition_variable condition;
bool stop;
};
// the constructor just launches some amount of workers
inline ThreadPool::ThreadPool(size_t threads)
: stop(false)
{
for(size_t i = 0;i<threads;++i)
workers.emplace_back(
[this]
{
for(;;)
{
std::function<void()> task;
{
std::unique_lock<std::mutex> lock(this->queue_mutex);
this->condition.wait(lock,
[this]{ return this->stop || !this->tasks.empty(); });
if(this->stop && this->tasks.empty())
return;
task = std::move(this->tasks.front());
this->tasks.pop();
}
task();
}
}
);
}
// add new work item to the pool
template<class F, class... Args>
auto ThreadPool::enqueue(F&& f, Args&&... args)
-> std::future<typename std::result_of<F(Args...)>::type>
{
using return_type = typename std::result_of<F(Args...)>::type;
auto task = std::make_shared< std::packaged_task<return_type()> >(
std::bind(std::forward<F>(f), std::forward<Args>(args)...)
);
std::future<return_type> res = task->get_future();
{
std::unique_lock<std::mutex> lock(queue_mutex);
// don't allow enqueueing after stopping the pool
if(stop)
throw std::runtime_error("enqueue on stopped ThreadPool");
tasks.emplace([task](){ (*task)(); });
}
condition.notify_one();
return res;
}
// the destructor joins all threads
inline ThreadPool::~ThreadPool()
{
{
std::unique_lock<std::mutex> lock(queue_mutex);
stop = true;
}
condition.notify_all();
for(std::thread &worker: workers)
worker.join();
}
#endif
5. 參考資料
- 100行實作執行緒池
- std::condition_variable 類介紹
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/3847.html
標籤:其他
上一篇:微信小程式面試題總結
