使用C++写一个线程池
时间: 2023-06-28 12:14:48 浏览: 93
下面是一个简单的C++线程池实现,仅供参考:
```c++
#include <iostream>
#include <vector>
#include <queue>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <functional>
#include <future>
class ThreadPool {
public:
ThreadPool(size_t thread_count) : stop(false) {
for (size_t i = 0; i < thread_count; ++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();
}
}
);
}
}
template<class F, class... Args>
auto 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;
}
~ThreadPool() {
{
std::unique_lock<std::mutex> lock(queue_mutex);
stop = true;
}
condition.notify_all();
for (std::thread& worker : workers)
worker.join();
}
private:
std::vector<std::thread> workers;
std::queue<std::function<void()>> tasks;
std::mutex queue_mutex;
std::condition_variable condition;
bool stop;
};
```
上面的代码中,`ThreadPool`类封装了一个线程池,提供了`enqueue()`方法用于向线程池中添加任务。当调用`enqueue()`方法时,线程池会将任务封装成一个`std::packaged_task`对象,并将其放入任务队列中。工作线程会从任务队列中取出任务并执行,直到线程池被销毁或者调用`stop()`方法停止线程池。
可以使用下面的代码测试线程池的功能:
```c++
#include <chrono>
#include <random>
int main() {
ThreadPool pool(4);
std::vector<std::future<int>> results;
std::random_device rd;
std::mt19937 gen(rd());
std::uniform_int_distribution<> dis(1, 100);
for (int i = 0; i < 8; ++i) {
results.emplace_back(
pool.enqueue([i, dis, &gen] {
std::cout << "task " << i << " start" << std::endl;
std::this_thread::sleep_for(std::chrono::seconds(dis(gen)));
std::cout << "task " << i << " end" << std::endl;
return i * i;
})
);
}
for (auto&& result : results)
std::cout << result.get() << ' ';
std::cout << std::endl;
return 0;
}
```
上面的代码创建了一个包含4个线程的线程池,并向线程池中添加了8个任务。每个任务会随机休眠1~100秒的时间,然后返回任务编号的平方。最后打印所有任务的返回值。
阅读全文