使用 std::async 结合 std::packaged_task 可以更好地控制其生命周期。 代码示例
时间: 2024-11-25 08:17:07 浏览: 31
`std::async` 结合 `std::packaged_task` 是一种优雅的方式来处理异步操作并控制其生命周期,特别适用于那些需要长期保留或者需要用户回调的情况。下面是一个简单的代码示例:
```cpp
#include <iostream>
#include <future>
#include <thread>
// 定义一个包装的异步任务
class MyTask {
public:
explicit MyTask(std::function<void()> task) : task_(task) {}
// 使用 packaged_task 接收任务,并允许外部调用完成任务
void start() {
future_ = std::packaged_task<void()>([this] { task_(); });
}
// 当需要执行时,调用这个包装的函数
void execute() {
if (!future_) {
throw std::runtime_error("Task has already been executed.");
}
future_.get();
}
private:
std::function<void()> task_;
std::packaged_task<void()> future_;
};
int main() {
// 创建一个异步任务
auto my_task = MyTask([]() {
std::cout << "Running long task...\n";
// 这里模拟一个耗时的操作
std::this_thread::sleep_for(std::chrono::seconds(5));
});
// 启动任务
std::thread worker_thread(my_task.start);
// 主线程等待一段时间后,手动执行任务
std::this_thread::sleep_for(std::chrono::seconds(2));
my_task.execute();
// 等待子线程结束
worker_thread.join();
return 0;
}
```
在这个例子中,`MyTask` 类封装了一个 `std::packaged_task`,它负责保存原始的任务并提供一个可调用的接口 `execute()`。主线程启动了任务,然后可以在适当的时候通过 `execute()` 来触发任务,而不是直接调用 `task_()`,这样就可以控制任务的执行时间。当 `future_` 被销毁时,`task_` 也不会被执行,实现了更好的资源管理和生命周期管理。
阅读全文
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![uml](https://img-home.csdnimg.cn/images/20250102104920.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)