gpt4 book ai didi

c++ - 当 std::future 准备好被检索时向主线程发送信号

转载 作者:可可西里 更新时间:2023-11-01 17:55:34 31 4
gpt4 key购买 nike

我正在尝试理解 std::asyncstd::future 系统。我不太明白的是,您如何处理运行多个异步“任务”,然后根据第一个、第二个等返回的内容运行一些额外的代码。

示例:假设您的主线程处于一个简单的循环中。现在,根据用户输入,您通过 std::async 运行多个函数,并将 future 保存在 std::list 中。

我的问题是,如何从 std::async 函数传回可以指定哪个 future 完成的信息?

我的主线程基本上处于消息循环中,我需要做的是让 std::async 运行的函数能够对消息进行排队,该消息以某种方式指定哪个 future 是完整的。问题是该函数无法访问 future 。

我是不是漏掉了什么?

这是我要完成的一些伪代码;如果有办法也有办法使用取消 token 调用“取消”请求,则加分。

class RequestA
{
public:
int input1;

int output1;
};

main()
{
while(1)
{
//check for completion
// i.e. pop next "message"
if(auto *completed_task = get_next_completed_task())
{
completed_task->run_continuation();
}

// other code to handle user input
if(userSaidRunA())
{
// note that I don't want to use a raw pointer but
// am not sure how to use future for this
RequestA *a = new RequestA();
run(a, OnRequestTypeAComplete);
}

}
}

void OnRequestTypeAComplete(RequestA &req)
{
// Do stuff with req, want access to inputs and output
}

最佳答案

不幸的是,C++11 std::future 不提供延续和取消。您只能从 std::future 检索结果一次。此外, future 从其析构函数中的 std::async block 返回。有一个小组由来自 Adob​​e 的 Sean Parent 领导。他们实现了 future , async , task应该如此。还可以像 when_all 这样继续工作, when_any .可能是您要找的东西。不管怎样,看看this project .代码质量好,易于阅读。

如果依赖于平台的解决方案也适合您,您可以检查它们。对于 Windows 我知道 PPL图书馆。它还具有取消和延续的原语。

关于c++ - 当 std::future 准备好被检索时向主线程发送信号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45852218/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com