gpt4 book ai didi

c++ - 如何在条件内的 Bool 方法上启动线程?

转载 作者:行者123 更新时间:2023-11-28 04:42:31 25 4
gpt4 key购买 nike

bool isTrue()
{
return true
}

int main ()
{
if (isTrue())
{
// Do something
}
}

我意识到这个示例代码没有意义,但逻辑并不重要,只是试图为问题设置它。如何调用 isTrue() 上的线程?通常,我会使用 std::thread t(//insert function here),但这不能在这里完成,因为线程不返回 bool。有什么体面的方法可以做到这一点吗?我对线程等还很陌生,所以我很容易不理解一些基本的东西。

最佳答案

as thread doesn't return a bool. Is there any decent way to do this?

std::async 是一种非常方便的异步启动任务的方法。它将返回的结果存储在“共享状态”中,以便我们稍后(准备就绪时)获取它

启动一个在后台运行isTrue()的异步任务,我们调用(后面可以通过fut访问结果)

std::future<bool> fut = std::async(std::launch::async, isTrue);

为了在我们需要的时候获得结果(即在 if 条件下),我们会调用

bool result = fut.get();

然后就可以在if语句中使用了。

if (result)
{
// Do something
}

你基本上可以将任何类型的函数传递给 std::async 并将结果存储在关联的 std::future 中。

关于c++ - 如何在条件内的 Bool 方法上启动线程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49930842/

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