C++实现简易线程池

2021-03-31 03:26

阅读:495

标签: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


评论


亲,登录后才可以留言!