C++11實現一個簡單的線程池
阿新 • • 發佈:2018-05-19
start art AI fun con var func iostream any
為了不讓手生,邊復習邊手擼了一個線程池,代碼量比較少,如下,用了一些C++11的實現,語言標準嘛,就是跨平臺的:
thread_poo.h
#ifndef _THREAD_POOL_ #define _THREAD_POOL_ #include<thread> #include<vector> #include<list> #include<queue> #include<functional> #include<condition_variable> using namespace std; class thread_pool { public: typedef std::function<void()> Task; void append(Task task); void worker(); thread_pool(int thread_nums); ~thread_pool(); vector<thread*> p_threads; queue<Task> p_task; mutex p_mutex; condition_variable_any p_condition; bool p_start; }; #endif // !_THREAD_POOL_H
thread_pool.cpp如下:
#include"thread_pool.h" thread_pool::thread_pool(int thread_nums) { p_start = true; for (int size = 0; size < thread_nums; size++) { thread* temp = new thread(bind(&thread_pool::worker,this)); p_threads.push_back(temp); } } void thread_pool::worker(){ while (p_start) { unique_lock<mutex> lk(p_mutex); p_condition.wait(lk, [this] {return this->p_task.size(); });//加鎖的原因很簡單,如果不加可能這個任務被其他的線程執行了 Task task= p_task.front(); p_task.pop(); lk.unlock(); task(); } } thread_pool::~thread_pool() { for (int size = 0; size < p_threads.size(); size++) { p_threads[size]->join(); delete p_threads[size]; } } void thread_pool::append(Task task) { p_task.push(task); p_condition.notify_one(); }
main如下:
#include"thread_pool.h" #include<iostream> using namespace std; void fun1() { int i = 0; while (i < 1000) { cout << "cat" << endl; i++; } } void fun2() { int i = 0; while (i < 1000) { cout << "dog" << endl; i++; } } int main() { thread_pool tp(10); tp.append(fun1); tp.append(fun2); return 0; }
歡迎留言指正!
C++11實現一個簡單的線程池