C++11线程池的用法

#include <iostream>
#include <vector>
#include <queue>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <functional>
#include <future>
#include <utility> // for std::move


class ThreadPool {
public:
	explicit ThreadPool(size_t numThreads) : stop(false)
	{
		for (size_t i = 0; i < numThreads; ++i)
		{
		//使用emplace_back向vector容器中加入工作的线程函数
			workers.emplace_back([this]
			{
				for (;;)    //等同于while
				{
					std::function<void()> task;
					
					std::unique_lock<std::mutex> lock(queue_mutex);
					condition.wait(lock, [this] { return stop || !tasks.empty(); });
					if (stop && tasks.empty()) return;
					task = tasks.front();
					tasks.pop();
					task();
				}
			});
		}
	}

	~ThreadPool()
	{

		std::unique_lock<std::mutex> lock(queue_mutex);
		stop = true;

		condition.notify_all();
		for (std::thread &worker : workers)
		{
			worker.join();
		}
	}

	template<typename Func, typename... Args>
	auto enqueue(Func&& func, Args&&... args) -> std::future<typename std::result_of<Func(Args...)>::type>  //推导返回类型
	{
		using return_type = typename std::result_of<Func(Args...)>::type;

		auto task = std::make_shared<std::packaged_task<return_type()>>(
			std::bind(std::forward<Func>(func), std::forward<Args>(args)...));

		std::future<return_type> res = task->get_future();  //通过get_feature获得执行结果
		{
			std::unique_lock<std::mutex> lock(queue_mutex);
			tasks.emplace([task]() { (*task)(); });    //任务加入队列   类似上面的emplace_back函数
		}
		condition.notify_one();    // 条件成立  通知一次
		return res;
	}


	
private:
	std::vector<std::thread> workers;
	std::queue<std::function<void()>> tasks;
	std::mutex queue_mutex;
	std::condition_variable condition;
	bool stop;
};



float doWork(float x)
{
	std::cout << "Processing " << x << " in thread " << std::this_thread::get_id() << std::endl;
	return x * x;
}


void ThreadPoolTest()
{
	ThreadPool pool(4); // 创建一个包含4个线程的线程池

	std::vector<std::future<float>> results;
	for (int i = 0; i < 8000; ++i) {
		results.emplace_back(pool.enqueue(doWork, i+0.01)); // 提交任务到线程池
	}

	for (auto& result : results) {
		std::cout << "Result: " << result.get() << std::endl; // 获取并打印结果
	}
}





int main()
{
	ThreadPoolTest();


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值