用Boost.Thread给出一个线程池实例
时间: 2023-07-01 19:23:30 浏览: 65
好的,以下是使用 Boost.Thread 实现线程池的示例代码:
```c++
#include <boost/thread.hpp>
#include <boost/thread/mutex.hpp>
#include <boost/thread/condition.hpp>
#include <queue>
class ThreadPool {
public:
ThreadPool(int num_threads) : num_threads_(num_threads), stop_(false) {
for (int i = 0; i < num_threads_; ++i) {
threads_.create_thread(boost::bind(&ThreadPool::worker_thread, this));
}
}
~ThreadPool() {
{
boost::unique_lock<boost::mutex> lock(mutex_);
stop_ = true;
cond_.notify_all();
}
threads_.join_all();
}
void enqueue(boost::function<void()> task) {
boost::unique_lock<boost::mutex> lock(mutex_);
tasks_.push(task);
cond_.notify_one();
}
private:
void worker_thread() {
while (!stop_) {
boost::function<void()> task;
{
boost::unique_lock<boost::mutex> lock(mutex_);
while (tasks_.empty() && !stop_) {
cond_.wait(lock);
}
if (stop_) {
return;
}
task = tasks_.front();
tasks_.pop();
}
task();
}
}
int num_threads_;
boost::thread_group threads_;
std::queue<boost::function<void()> > tasks_;
boost::mutex mutex_;
boost::condition_variable cond_;
bool stop_;
};
```
这个线程池可以通过 `ThreadPool pool(num_threads)` 构造函数创建,其中 `num_threads` 参数指定线程池中线程的数量。任务可以通过 `pool.enqueue(task)` 方法提交到线程池中执行,其中 `task` 是一个 `boost::function<void()>` 类型的可调用对象。
该线程池使用一个任务队列来存储待执行的任务,并使用互斥量和条件变量来实现线程同步。在析构函数中,首先设置 `stop_` 标志,然后通知所有等待线程的条件变量,以便它们退出。最后,等待所有线程结束并加入到线程组中。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)