c++11实现安全线程池类
时间: 2023-08-30 08:10:30 浏览: 103
下面是一个基于C++11实现的安全线程池类的示例代码:
```c++
#include <iostream>
#include <queue>
#include <mutex>
#include <thread>
#include <condition_variable>
#include <functional>
class ThreadPool {
public:
ThreadPool(int num_threads) : stop(false) {
for (int i = 0; i < num_threads; ++i) {
threads.emplace_back(
[this] {
while (true) {
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();
}
}
);
}
}
~ThreadPool() {
{
std::unique_lock<std::mutex> lock(queue_mutex);
stop = true;
}
condition.notify_all();
for (std::thread& thread : threads) {
thread.join();
}
}
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;
}
private:
std::vector<std::thread> threads;
std::queue<std::function<void()>> tasks;
std::mutex queue_mutex;
std::condition_variable condition;
bool stop;
};
```
该线程池类使用C++11中的`std::thread`和`std::mutex`等多线程库实现。它可以通过调用`enqueue`方法向线程池中添加任务,并返回一个`std::future`对象,以便在需要时获取任务的返回值。同时,由于该线程池类是安全的,因此多个线程可以同时调用`enqueue`方法而不会发生竞争条件。当线程池被销毁时,所有线程都会被正确地加入。
示例用法:
```c++
#include <chrono>
#include <iostream>
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::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;
}
```
该示例在创建线程池后,使用`enqueue`方法将8个任务添加到线程池中,并在每个任务中输出一些文本,并将返回值设置为任务的索引的平方。它还使用`std::future`对象获取每个任务的返回值,并将它们打印到控制台。
阅读全文