C++11实现一个简单的线程池

为了不让手生,边复习边手撸了一个线程池,代码量比较少,如下,用了一些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;
}

  欢迎留言指正!

猜你喜欢

转载自www.cnblogs.com/xdmonkey/p/9060452.html