c++11自定义线程池

为了保证退出程序前,所有运行的线程都已经停止。我引入了信号量,对线程池进行改造。改造实现代码如下。

#pragma once
#include<queue>
#include<thread>
#include<mutex>
#include<condition_variable>
#include<iostream>
#include"Semaphore.h"
using namespace std;

class Thread
{
public:
	typedef void(*TheadFuncion)();
	thread* th = nullptr;
	void* data;
	TheadFuncion func;
	bool exit = false;
	bool isThreadEnd = false;
	bool idle = true;

	Semaphore taskSemaphore;
	Semaphore quitSemaphore;

	void Func()
	{
		isThreadEnd = false;
		while (!exit) {
			this->func();
			idle = true;
			taskSemaphore.wait();
		}

		isThreadEnd = true;
		quitSemaphore.signal();
	}

	bool Start(Thread::TheadFuncion func)
	{
		if (!idle) {
			return false;
		}
		idle = false;
		this->func = func;

		if (nullptr == th) {
			th = new thread([&]() {
				Func();
			});
			th->detach();
		}
		else {
			taskSemaphore.signal();
		}
		return true;
	}

	bool IsIdle() {
		return idle;
	}

	void Stop()
	{
		exit = true;
		if (!isThreadEnd) {
			taskSemaphore.signal();
			quitSemaphore.wait();
		}
		delete th;
	}

	Thread(){
	}

	~Thread(){
		if (nullptr == th) {
			exit = true;
		}else {
			if (!exit) {
				Stop();
			}
		}
	}
};



class ThreadPool
{
public:
	vector<Thread*> threads;
	typedef std::vector<Thread*>::iterator Iterator;
	mutex mtx;
	bool isEnd = false;

public:
	ThreadPool(int threadCount)
	{
		for (int i = 0; i < threadCount; i++) {
			Thread* thread = new Thread();
			threads.push_back(thread);
		}
	}

	~ThreadPool() {
		Iterator iter = threads.begin();
		while (iter != threads.end()) {
			if (nullptr != *iter) {
				delete *iter;
				iter = threads.erase(iter);
			}
			else {
				iter++;
			}
		}
		isEnd = true;
	}

	bool Add(Thread::TheadFuncion func) {
		mtx.lock();
		Iterator iter = threads.begin();
		bool isAddOk = false;
		while (iter != threads.end()) {
			if ((*iter)->IsIdle()) {
				isAddOk = (*iter)->Start(func);
				if (!isAddOk) {
					iter++;
				}
				else {
					break;
				}
			}
			else {
				iter++;
			}
		}
		mtx.unlock();
		return isAddOk;
	}

};
 信号量实现代码如下:

#include <mutex>
#include <condition_variable>
#include<iostream>
using namespace std;

class Semaphore {
private:
	int count;
	int wakeups;
	std::mutex mutex;
	std::condition_variable condition;


public:
	Semaphore(int value = 0) :count(value), wakeups(0) {}

	void wait() {
		std::unique_lock<std::mutex> lock(mutex);
		if (--count < 0) {
			condition.wait(lock, [&]()->bool {return wakeups > 0; });
			--wakeups;
		}
	}

	void signal() {
		std::lock_guard<std::mutex> lock(mutex);
		if (++count <= 0) {
			++wakeups;
			condition.notify_one();
		}
	}
};
信号量代码引用链接:

http://www.360doc.com/content/15/0303/20/203028_452313531.shtml



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值