c++11 线程池

#include "stdafx.h"
#include "ThreadPool.h"

ThreadPool::ThreadPool(int thread_num) : stop_(false)
{
	for (int count = 0; count < thread_num; count++){
		pools_.emplace_back(&work, this);
	}
}

ThreadPool::~ThreadPool()
{
	stop_.store(true);
	c_.notify_all();
	for (std::thread& thread : pools_){
		thread.join();
	}
}

std::shared_ptr<Task>  ThreadPool::get_one_task()
{
	std::unique_lock<std::mutex> lock(mutex_);
	c_.wait(lock, [this](){
		return stop_.load() || !task_.empty();
	});
	if (!task_.empty()){
		std::shared_ptr<Task> ptask = std::move(task_.front());
		task_.pop();
		return ptask;
	}
	return std::make_shared<Task>();
}

void  ThreadPool::work(ThreadPool *pthis)
{
	while (!pthis->stop_.load()){	
		auto task = pthis->get_one_task();
		task->run();
	}
}

void ThreadPool::commit(std::shared_ptr<Task> task)
{
	std::unique_lock<std::mutex> lock(mutex_);
	task_.emplace(task);
	c_.notify_one();
}



#pragma once
#include <memory>
#include <thread>
#include <mutex>
#include <queue>
#include <condition_variable>
#include <vector>
#include <atomic>

class Task
{
public:
	virtual void run(){
	}
};

class ThreadPool
{
public:
	ThreadPool(int thread_num = 5);
	virtual ~ThreadPool();

	void commit(std::shared_ptr<Task> task);
	static void work(ThreadPool *pthis);
	std::shared_ptr<Task> get_one_task();

private:
	std::vector<std::thread> pools_;
	std::mutex mutex_;
	std::condition_variable c_;
	std::atomic<bool> stop_;
	std::queue<std::shared_ptr<Task>> task_;
};


class NewTask : public Task
{
public:
	virtual void run(){
		//MessageBoxA(NULL, "121", "", MB_OK);
		mu.lock();
		std::cout << "id =" << std::this_thread::get_id() << std::endl;
		mu.unlock();
	}
};

int _tmain(int argc, _TCHAR* argv[])
{
	ThreadPool pool(3);
	pool.commit(std::make_shared<NewTask>());
	pool.commit(std::make_shared<NewTask>());
	pool.commit(std::make_shared<NewTask>());
	pool.commit(std::make_shared<NewTask>());
	pool.commit(std::make_shared<NewTask>());
	pool.commit(std::make_shared<NewTask>());
	pool.commit(std::make_shared<NewTask>());
	pool.commit(std::make_shared<NewTask>());

	std::this_thread::sleep_for(std::chrono::seconds(10));
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值