简单的线程池

本文介绍了一个简单的线程池实现方案,包括线程池的基本原理、核心类CThreadPool的设计与实现,以及通过示例演示如何使用该线程池来调度不同任务。

      一个简单的线程池的实现,基本原理:创建线程池的时候即创建多个线程,且让它们处于挂起状态,然后等待用户需要创建一个线程的时候,恢复其中一个被挂起的线程,并执行用户指定的线程函数。执行完毕后再次挂起这个线程,直到用户再次需要创建新的线程的时候,再恢复一个挂起的线程。最后程序退出,关闭所有线程。

 

ThreadPool 头文件:

 

ThreadPool 源文件:

 

测试代码:

 

执行结果:

### 简易线程池实现概述 在C++中,线程池是一种用于管理多个线程并分配任务的机制。通过线程池,可以减少线程创建和销毁的开销,提高程序的性能。一个简易的线程池通常包括线程管理、任务队列和任务调度等功能。以下是一个基于C++11标准的简易线程池实现示例,展示了如何创建线程池、添加任务以及执行任务。 ### 示例代码 ```cpp #include <iostream> #include <vector> #include <thread> #include <queue> #include <functional> #include <mutex> #include <condition_variable> #include <future> class ThreadPool { public: ThreadPool(size_t numThreads); ~ThreadPool(); template<class F, class... Args> auto enqueue(F&& f, Args&&... args) -> std::future<typename std::result_of<F(Args...)>::type>; private: // 工作线程池 std::vector<std::thread> workers; // 任务队列 std::queue<std::function<void()>> tasks; // 同步 std::mutex queue_mutex; std::condition_variable condition; bool stop; }; // 线程池构造函数 inline ThreadPool::ThreadPool(size_t numThreads) : stop(false) { for (size_t i = 0; i < numThreads; ++i) workers.emplace_back([this] { for (;;) { 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(); } }); } // 线程池析构函数 inline ThreadPool::~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 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.emplace([task]() { (*task)(); }); } condition.notify_one(); return res; } ``` ### 使用示例 ```cpp #include <iostream> #include <chrono> void exampleTask(int id) { std::cout << "Task " << id << " is being processed by thread " << std::this_thread::get_id() << std::endl; std::this_thread::sleep_for(std::chrono::seconds(1)); } int main() { ThreadPool pool(3); // 创建包含3个线程的线程池 for (int i = 0; i < 10; ++i) { pool.enqueue([i]() { exampleTask(i); }); } return 0; } ``` ### 解释 1. **线程池构造函数**:`ThreadPool`类的构造函数接收线程数量作为参数,并创建相应数量的工作线程。每个工作线程都在一个无限循环中等待任务。 2. **任务队列**:使用`std::queue`存储待处理的任务。任务被封装为`std::function<void()>`对象。 3. **同步机制**:使用`std::mutex`和`std::condition_variable`来保护任务队列,并在任务到达时通知工作线程。 4. **任务添加**:`enqueue`函数模板用于将任务添加到队列中。它返回一个`std::future`对象,可以用来获取任务的结果。 5. **线程池析构**:在析构函数中,设置`stop`标志以通知所有工作线程停止,并等待它们完成当前任务。 这个线程池实现可以用于处理多个并发任务,并且可以扩展以适应更复杂的应用场景[^3]。 ###
评论 3
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值