multithreading - 如何从 std::async 线程中启动 std::async 线程,并在第二个启动后让第一个死掉?
问题描述
我想要实现的是拥有和自主的异步线程磨,异步 A 完成它的任务,启动异步 B 并死亡。async B 重复执行相同的操作。
示例代码:main.cpp
class operation_manager : public std::enable_shared_from_this<operation_manager> {
public:
operation_manager() {}
void do_operation(void) {
std::function<void(std::shared_ptr<operation_manager>)> fun( [this](std::shared_ptr<operation_manager> a_ptr) {
if( a_ptr != nullptr ) {
a_ptr->do_print();
}
} );
i_ap.read(fun, shared_from_this());
}
void do_print(void) {
std::cout << "Hello world\n" << std::flush;
do_operation();
}
private:
async_operation i_ap;
};
int main(int argc, const char * argv[]) {
auto om( std::make_shared<operation_manager>() );
om->do_operation();
while(true) {
std::this_thread::sleep_for(std::chrono::seconds(1));
}
return 0;
}
示例代码:async_operation.hpp
class async_operation {
public:
async_operation() {};
template<typename T>
void read(std::function<void(std::shared_ptr<T>)> a_callback, std::shared_ptr<T> a_ptr) {
auto result( std::async(std::launch::async, [&]() {
wait();
a_callback(a_ptr);
return true;
}) );
result.get();
}
private:
void wait(void) const {
std::this_thread::sleep_for(std::chrono::seconds(1));
}
};
解决方案
您的错误是在异步任务内部调用result.get()
- 这导致它阻塞并等待下一个任务完成。等待你需要做的是将期货保存在某个地方,然后让它们运行。
这是 async_operation 类的修改代码:
std::vector<std::shared_ptr<std::future<bool>>> results;
class async_operation {
public:
async_operation() {};
template<typename T>
void read(std::function<void(std::shared_ptr<T>)> a_callback, std::shared_ptr<T> a_ptr) {
results.push_back(std::make_shared<std::future<bool>>(std::async(std::launch::async, [=]() {
wait();
a_callback(a_ptr);
return true;
})));
}
private:
void wait(void) const {
std::this_thread::sleep_for(std::chrono::seconds(1));
}
};
推荐阅读
- salesforce - 集成 Salesforce 与 Docusign 无效类型:dfsle.Envelope
- microsoft-dynamics - 如何通过 UI 在测试代码单元中创建新客户?
- css - CSSTransition 中的“出现”不能按预期工作
- python - 如何将现有的 django 对象复制到另一个表以进行临时存储?
- python - 在 xarray 绘图上方绘制底图
- r - r ggplot 等高线密度
- python - 可以将黑色配置为忽略导入吗?
- c# - 我如何控制所有这些我不想在选定的入住和退房时间找到预订的情况?
- arrays - 结构数组作为参数及其成员访问
- html - 选择内部 flex 元素时,文本选择背景在 Safari 中变得不可见