用C++实现一个线程池DEmo
时间: 2024-04-11 20:06:29 浏览: 174
C++实现的线程池
以下是一个简单的C++线程池Demo:
```cpp
#include <iostream>
#include <queue>
#include <thread>
#include <mutex>
#include <condition_variable>
class ThreadPool {
public:
ThreadPool(size_t size = 4) {
for (size_t i = 0; i < size; ++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 = false;
};
int main() {
ThreadPool pool;
std::vector<std::future<int>> results;
for (int i = 0; i < 8; ++i) {
results.emplace_back(
pool.enqueue([i] {
std::cout << "hello " << i << std::endl;
std::this_thread::sleep_for(std::chrono::seconds(1));
std::cout << "world " << i << std::endl;
return i*i;
})
);
}
for (auto&& result : results)
std::cout << result.get() << ' ';
std::cout << std::endl;
return 0;
}
```
这个例子中,线程池ThreadPool的构造函数会创建size个线程,这些线程会在无限循环中从任务队列tasks中取出任务并执行,当线程池被销毁时,每个线程都会退出循环并join到主线程中。
enqueue函数用于向任务队列中加入任务,返回一个std::future对象,表示将来可以获得任务的返回值。如果任务队列已经被停止,enqueue函数会抛出std::runtime_error异常。
在主函数中,我们首先创建了一个ThreadPool对象pool,然后向任务队列中加入了8个任务,每个任务会输出"hello i",然后睡眠1秒钟,最后输出"world i",并返回i的平方。最后,我们通过std::future对象获取每个任务的返回值并输出。
阅读全文