C++ 线程池 代码举例
时间: 2023-12-01 09:37:19 浏览: 100
代码总共分两部分:ThreadPool.h和example.cpp。这个线程池的实现基于C++11版本以上,可以添加各种类型的线程任务,并且能够获得任务的返回值。下面是一个代码举例:
```cpp
#include <iostream>
#include <functional>
#include <thread>
#include <vector>
#include <queue>
#include <future>
#include <mutex>
#include <condition_variable>
class ThreadPool {
public:
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->queueMutex);
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<typename F, typename... Args>
auto enqueue(F&& f, Args&&... args) -> std::future<typename std::result_of<F(Args...)>::type> {
using returnType = typename std::result_of<F(Args...)>::type;
auto task = std::make_shared<std::packaged_task<returnType()>>(
std::bind(std::forward<F>(f), std::forward<Args>(args)...)
);
std::future<returnType> result = task->get_future();
{
std::unique_lock<std::mutex> lock(queueMutex);
if (stop) {
throw std::runtime_error("enqueue on stopped ThreadPool");
}
tasks.emplace([task]() { (*task)(); });
}
condition.notify_one();
return result;
}
~ThreadPool() {
{
std::unique_lock<std::mutex> lock(queueMutex);
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 queueMutex;
std::condition_variable condition;
bool stop;
};
int main() {
ThreadPool pool(4);
std::vector<std::future<int>> results;
for (int i = 0; i < 8; ++i) {
results.emplace_back(
pool.enqueue([i] {
std::this_thread::sleep_for(std::chrono::seconds(1));
return i * i;
})
);
}
for (auto&& result : results) {
std::cout << result.get() << ' ';
}
std::cout << std::endl;
return 0;
}
```
此代码使用了C++11的多线程功能,通过使用std::packaged_task和std::future获取任务的返回值,并使用std::function封装任务。线程池的大小可以通过构造函数参数进行指定。在主函数中,我们向线程池中添加了8个任务,并通过std::future获取了每个任务的返回值,并输出到控制台。
阅读全文