c++线程池

本文介绍了如何使用C++实现一个简单的线程池ThreadPool,通过线程池管理并发任务,展示了如何创建线程、任务队列的使用以及停止线程的操作。
#include <iostream>
#include <thread>
#include <mutex>
#include <string> 
#include <condition_variable>
#include <queue>
#include <vector>
#include <functional>


class ThreadPool
{
public:
	ThreadPool(int numThreads) : stop(false)
	{
		for (int i = 0; i < numThreads ;i++)
		{
			threads.emplace_back
								(
									[this]()
									{
										while (1)
										{
											std::unique_lock<std::mutex> lock(mtx);
											condition.wait(lock,
												[this]()
												{
													return !tasks.empty() || stop;
												}
											);

											if (stop && tasks.empty()) return;

											std::function<void()> task(std::move(tasks.front()));
											tasks.pop();
											lock.unlock();

											task();
										}

									}
								);
		}
	}

	~ThreadPool()
	{
		{
			std::unique_lock<std::mutex> lock(mtx);
			stop = true;
		}
		condition.notify_all();

		for (auto& t : threads)
		{
			t.join();
		}

	}

	template<class F, class ... Args>
	void enqueue(F&& f, Args&&... args)
	{
		std::function<void()> task = std::bind(std::forward<F>(f), std::forward<Args> (args) ...);

		std::unique_lock<std::mutex> lock(mtx);
		tasks.emplace(std::move(task));
		condition.notify_one();
	}

private:
	std::vector<std::thread> threads;
	std::queue < std::function<void()>> tasks;

	std::mutex mtx;
	std::condition_variable condition;

	bool stop;
};


int main()
{
	ThreadPool pool(4);
	for (size_t i = 0; i < 10; i++)
	{
		pool.enqueue(
			[i]()
			{
				std::cout << "task:" << i << "is running" << std::endl;
				std::this_thread::sleep_for(std::chrono::seconds(1));
				std::cout << "task:" << i << "is done" << std::endl;

			}
		);
	}

	return 0;
}

### C++ 线程池实现教程 #### 创建线程池类 为了创建一个简单的C++线程池,定义`ThreadPool`类来封装多个工作线程。该类负责管理一组预先启动的线程,并分配任务给这些线程执行。 ```cpp class ThreadPool { public: /// @brief Constructor that initializes the thread pool with a specified number of threads. explicit ThreadPool(size_t threads = std::thread::hardware_concurrency()) : stop(false) { if (threads == 0) { threads = 1; } for (size_t i = 0; i < threads; ++i) { workers.emplace_back( [this] { while (true) { std::function<void()> task; { std::unique_lock<std::mutex> lock(this->queue_mutex); this->condition.wait(lock, [this]{ return this->stop || !this->tasks.empty(); }); if (this->stop && this->tasks.empty()) { return; } task = std::move(this->tasks.front()); this->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<class F, class... Args> auto enqueue(F&& f, Args&&... args) -> std::future<typename std::result_of<F(Args...)>::type>; private: // Work queue and synchronization primitives std::vector<std::thread> workers; std::queue<std::function<void()>> tasks; std::mutex queue_mutex; std::condition_variable condition; bool stop; }; ``` 上述代码展示了如何通过构造函数初始化一定数量的工作线程[^4]。每个线程都在无限循环中等待新任务的到来;当接收到停止信号并且队列为空时,则退出循环并结束线程。 #### 添加任务到线程池 为了让外部能够向线程池提交新的任务,在`ThreadPool`类内部实现了模板成员函数`enqueue()`用于接收任意类型的可调用对象作为参数,并将其放入任务队列中等待被执行: ```cpp template<class F, class... Args> auto ThreadPool::enqueue(F&& f, Args&&... args) -> std::future<typename std::result_of<F(Args...)>::type> { using return_type = typename std::result_of<F(Args...)>::type; auto task = std::make_shared< std::packaged_task<return_type()> >( std::bind(std::forward<F>(f), std::forward<Args>(args)...) ); std::future<return_type> res = task->get_future(); { std::unique_lock<std::mutex> lock(queue_mutex); // 不允许再添加新任务的情况处理 if(stop){ throw std::runtime_error("enqueue on stopped ThreadPool"); } tasks.push([task]() { (*task)(); }); } condition.notify_one(); return res; } ``` 此段代码说明了怎样安全地将任务加入到共享的任务队列里,并通知其中一个正在休眠中的工作者线程开始处理这个新到来的任务[^5]。 #### 测试线程池功能 最后提供了一个简单例子展示如何使用自定义的线程池来进行并发计算: ```cpp void* MyTaskFunc(void* arg) { int* i = static_cast<int*>(arg); printf("[MyTaskFunc]: thread[%lu] is working on %d\n", pthread_self(), *i); delete i; return nullptr; } int main(){ ThreadPool pool(10); // 初始化具有十个线程的线程池 for(int i=0;i<100;++i){ int* p=new int(i); pool.enqueue(MyTaskFunc,p); } return EXIT_SUCCESS; } ``` 这段程序片段演示了如何实例化一个含有固定数目线程的线程池,并连续不断地往里面塞入一百个小任务供其异步完成[^2]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值