C++11实现线程池

一个完备的线程池例子

#include <iostream>
#include <thread>
#include <vector>
#include <queue>
#include <mutex>
#include <condition_variable>
#include <functional>
#include <future>

class ThreadPool
{
public:
	explicit ThreadPool(int numThreads) : stop(false)
	{
		// 创建指定数量的线程,并将它们绑定到 workerFunction 函数
		if (numThreads < 1) numThreads = 1;
		for (int i = 0; i < numThreads; i++)
		{
			workers.emplace_back(&ThreadPool::workerFunction, this);
		}
	}

	template<class F, class... Args>
	auto enqueue(F&& f, Args&&... args)
		->std::future<decltype(f(args...))>
	{
		using return_type = decltype(f(args...));
		// 创建一个 packaged_task,将函数和参数绑定起来
		auto task = std::make_shared<std::packaged_task<return_type()>>(
			std::bind(std::forward<F>(f), std::forward<Args>(args)...)
		);
		std::future<return_type> result = task->get_future();
		{
			std::unique_lock<std::mutex> lock(queueMutex);
			if (stop)
				throw std::runtime_error("Enqueue on stopped Threadpool");
			tasks.emplace([task] {(*task)(); });
		}
		// 通知一个等待中的线程有新任务可执行
		condition.notify_one();
		return result;
	}

	~ThreadPool()
	{
		{
			std::lock_guard<std::mutex> lock(queueMutex);
			stop = true;
		}
		// 通知所有线程停止并等待它们结束
		condition.notify_all();
		for (std::thread& worker : workers)
			worker.join();
	}
private:
	void workerFunction()
	{
		while (true)
		{
			std::function<void()> task;
			{
				std::unique_lock<std::mutex> lock(queueMutex);
				/* 
				如果线程池被要求停止且任务队列为空,则线程结束
				调用过程先判断lamda表达式,如果true则继续执行,获取互斥锁资源,
				false则调用wait方法阻塞线程,释放互斥锁资源
				条件变量唤醒时,还是先判断lamda表达式,过程同上
				*/
				condition.wait(lock, [this] {return stop || !tasks.empty(); });
				if (stop && tasks.empty())
					return;
				// 从队列中取出一个待执行的任务
				task = std::move(tasks.front());
				tasks.pop();
			}
			task();
		}
	}
private:
	std::vector<std::thread> workers; // 线程池中的线程
	std::queue<std::function<void()>> tasks; // 任务队列
	std::mutex queueMutex; // 互斥量,用于保护任务队列
	std::condition_variable condition; // 条件变量,用于线程等待和唤醒
	bool stop;	// 标志是否停止线程池
};

int myFunc(int id)
{
	std::cout << "Task " << id << " is running." << std::endl;
	return id * id;
}

int main()
{
	ThreadPool pool(4);// 创建一个线程池,包含 4 个线程
	// 添加任务到线程池
	std::vector<std::future<int> > results;
	for (int i = 0; i < 10; i++)
	{
		results.push_back(pool.enqueue(&myFunc, i));
	}
	// 获取任务的返回值
	for (auto& result : results)
	{
		std::cout << "result: " << result.get() << std::endl;
	}

	return 0;
}

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值