c++11 執行緒池實現以及示例
阿新 • • 發佈:2019-02-16
執行緒池的使用在工作中非常普遍,對於java,python而言執行緒池使用還是比較方便。去年年底由於工作需要,用c++搭建一套工程程式碼,需要使用執行緒池,但是C++中並沒有現有的執行緒池,為了快速開發,以及程式碼的穩定還是google在github上面找到了一個不錯的C++11實現的版本,然後做了一點修改(相容伺服器gcc4.7)。
通過這一個執行緒池的實現,收穫如下:
1. 更加深入的理解了執行緒池
2. 熟悉了C++11的,模板,mutex, condition_variable, std::function, std::bind, std::unique_lock等的使用
下面首先給出一個簡單的應用場景,阻塞等待請求,或者事件(例如epoll事件),然後將資料以及handle壓入執行緒池處理,這樣無需等待handle函式處理完,即可等待下一次的請求或者事件(相當於是非同步)。
//建立一個還有5個執行緒的執行緒池
ThreadPool tp(5);
while(true){
// 阻塞的等待http的請求資料data
data = wait_req_from_http();
//將資料壓入執行緒池中處理,其中process_data_function為處理data的函式
tp.enqueue(data , process_data_function);
}
下面給出完整程式碼,只有一個.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:
// 執行緒池
std::vector< std::thread > workers;
// 任務佇列
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)
{
//建立n個執行緒,每個執行緒等待是否有新的task, 或者執行緒stop(要終止)
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);
//執行緒會一直阻塞,直到有新的task,或者是執行緒要退出
this->condition.wait(lock,
[this]{ return this->stop || !this->tasks.empty(); });
//執行緒退出
if(this->stop && this->tasks.empty())
return;
//將task取出
task = std::move(this->tasks.front());
//佇列中移除以及取出的task
this->tasks.pop();
}
//執行task,完了則進入下一次迴圈
task();
}
}
);
}
// add new work item to the pool
// 將佇列壓入執行緒池,其中f是要執行的函式, args是多有的引數
template<class F, class... Args>
auto ThreadPool::enqueue(F&& f, Args&&... args)
-> std::future<typename std::result_of<F(Args...)>::type>
{
//返回的結果的型別,當然可以根據實際的需要去掉這個(gcc4.7的c++11不支援)
using return_type = typename std::result_of<F(Args...)>::type;
//將函式handle與引數繫結
auto task = std::make_shared< std::packaged_task<return_type()> >(
std::bind(std::forward<F>(f), std::forward<Args>(args)...)
);
//after finishing the task, then get result by res.get() (mainly used in the invoked function)
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)(); });
}
//添加了新的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();
}
下面給出執行的示例以及結果(推薦使用CLion):
//執行緒池要執行的任務
//模擬下載,sleep 2S
void dummy_download(std::string url){
std::this_thread::sleep_for(std::chrono::seconds(3));
std::cout<<" complete download: "<<url<<std::endl;
}
//根據id返回使用者名稱
std::string get_user_name(int id){
std::this_thread::sleep_for(std::chrono::seconds(2));
return "user_" + std::to_string(id);
}
執行緒池使用示例:
ThreadPool tp(5);
//執行緒執行結果的返回
std::vector<std::future<std::string>> vecStr;
// 下載對應的url連結,沒有返回值
tp.enqueue(dummy_download, "www.baidu.jpg");
tp.enqueue(dummy_download, "www.yy.jpg");
//資料庫根據id查詢user name
vecStr.emplace_back(tp.enqueue(get_user_name, 101));
vecStr.emplace_back(tp.enqueue(get_user_name, 102));
//輸出執行緒返回的值,實際中可以不要
std::future<void> res1 = std::async(std::launch::async, [&vecStr](){
for (auto &&ret:vecStr) {
std::cout<<"get user: "<<ret.get();
}
std::cout<<std::endl;
});
執行結果如下: