C++实现单例线程池

摘要:本文使用C++实现了一个单例的线程池,创建8个线程,可以执行相应的任务。

#include <iostream>
#include <thread>
#include <semaphore.h>
#include <mutex>
#include <queue>
#include <list>

class TaskBase{
	public:
	    virtual void DoWork() = 0;
};

class downloadTask: public TaskBase{
	public:
		void DoWork() override{
			std::cout << "downloadTask thread id=" << std::this_thread::get_id() << std::endl;
		}
};

class ThreadPool{
	public:
		static ThreadPool& getInstance();
		void append(TaskBase* task);
		~ThreadPool();
	private:
		ThreadPool(int threadNum = 8);
		ThreadPool(const ThreadPool&);
		ThreadPool& operator = (const ThreadPool&);
		
		static void* worker(void* arg);
		void run();
		
	private:
		static ThreadPool pInstance;
		std::queue<TaskBase*> m_workQueue;
		std::mutex m_lock;
		sem_t m_sem;
		std::vector<std::thread*> m_threadList;
		bool m_is_stop = true;
}; 

ThreadPool ThreadPool::pInstance;

ThreadPool& ThreadPool::getInstance(){
	return pInstance;
}

ThreadPool::ThreadPool(int threadNum){
	sem_init(&m_sem, 0, 0);
	for(int i = 0; i < threadNum; i++){
		std::thread *t = new std::thread(worker, this);
		t->detach();
		m_threadList.push_back(t);
		std::cout << "create thread id=" << i + 1 << std::endl;
	}
}

ThreadPool::~ThreadPool(){
	m_is_stop = false;
	sem_destroy(&m_sem);
	for(int i = 0; i < m_threadList.size(); i++){
		delete m_threadList[i]; 
	}
}

void* ThreadPool::worker(void* arg){
	ThreadPool* pool = (ThreadPool*)arg;
	pool->run();
	return pool;
}

void ThreadPool::append(TaskBase* task){
	m_lock.lock();
	m_workQueue.push(task);
	m_lock.unlock();
	sem_post(&m_sem);
	std::cout << "append task" << std::endl;
}

void ThreadPool::run(){
	//每一个线程的消息循环 
	while(m_is_stop){
		sem_wait(&m_sem);
		m_lock.lock();
		TaskBase* task = m_workQueue.front();
		m_workQueue.pop();
		m_lock.unlock();
		
		task->DoWork();
		
		delete task;
	} 
}

#define threadPool ThreadPool::getInstance()

int main(){
	std::cout << "Threads create successfully!" << std::endl << std::endl;
	TaskBase *task = new downloadTask();
	threadPool.append(task);
	threadPool.append(task);
	threadPool.append(task);
	threadPool.append(task);
	threadPool.append(task);
	threadPool.append(task);
	threadPool.append(task);
	return 0;
}

运行结果:

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值