C++实现简易线程池
标签:namespace 简易 vector empty back unique out this function
#include
#include
#include
#include
#include
#include
#include
using namespace std;
class ThreadPool {
private:
typedef function Task;
public:
ThreadPool(int);
~ThreadPool();
bool start();
void put(Task task);
queue q;
private:
Task take();
int threadnum;
vector workers;
mutex mtx;
condition_variable cv;
void workfunc();
bool stop;
};
ThreadPool::ThreadPool(int num)
:threadnum(num),
stop(false)
{}
ThreadPool::~ThreadPool() {
stop = true;
cv.notify_all();
for (int i = 0; i ul(mtx);
q.emplace(task);
cv.notify_one();
}
ThreadPool::Task ThreadPool::take() {
unique_lock ul(mtx);
cv.wait(ul, [this]() {
return !q.empty() || stop;
});
if (stop) return nullptr;
Task ret(move(q.front()));
q.pop();
return move(ret);
}
void ThreadPool::workfunc() {
while (!stop) {
Task t = take();
t();
}
}
void func1() {
for (int i = 0; i
C++实现简易线程池
标签:namespace 简易 vector empty back unique out this function
原文地址:https://www.cnblogs.com/wasi-991017/p/14593801.html
文章来自:
搜素材网的
编程语言模块,转载请注明文章出处。
文章标题:
C++实现简易线程池
文章链接:http://soscw.com/index.php/essay/70276.html
评论