如何在C++;11? 是否可以在C++程序?< /P>上启动异步线程?

如何在C++;11? 是否可以在C++程序?< /P>上启动异步线程?,c++,multithreading,macos,asynchronous,C++,Multithreading,Macos,Asynchronous,像 在mac上,它对我不起作用,主程序等待返回 我想从我的程序开始启动异步线程,然后关闭它。。。没有任何同步或类似的东西 我使用XC+使用C++ 11。 如果你能给我一个解决方案,那就太好了 非常感谢您应该指定希望线程通过作为第一个参数传递来异步运行。否则,运行时系统可以选择推迟启动: #include <future> void function() { // do asynchronous stuff. } int main() { std::future&l

在mac上,它对我不起作用,主程序等待返回

我想从我的程序开始启动异步线程,然后关闭它。。。没有任何同步或类似的东西

我使用XC+使用C++ 11。 如果你能给我一个解决方案,那就太好了


非常感谢

您应该指定希望线程通过作为第一个参数传递来异步运行。否则,运行时系统可以选择推迟启动:

#include <future>

void function()
{
    // do asynchronous stuff.
}

int main()
{
    std::future<void> fut = std::async(std::launch::async, function);

    // do other stuff

    fut.get(); // synchronize threads
}
#包括
空函数()
{
//做异步的事情。
}
int main()
{
std::future fut=std::async(std::launch::async,函数);
//做其他事情
fut.get();//同步线程
}

那应该行。

也许你想用一个普通的?不,我需要一个异步线程,我不能同步线程,原因如下:在我的线程中有一个指向URL的请求循环,要获得json,如果我同步这个线程,我的程序有点滞后。但是如果你创建一个线程,它是“异步的”,它将独立于你的主线程运行。然而,在我看来,你似乎想用,然后它将在后台运行,您可以随时得到结果。为什么不
auto fut=…
?@NathanOliver可能是为了清楚起见,在这种情况下。@NathanOliver我会使用
auto
,但是在这个例子中,它会模糊OP的类型。因此,最好保持显式。非常感谢!我只是OSX的新手。@Galik,但类型不一定是
std::future
<代码> STD::Acycor()/Case>返回<代码> STD::C++中的未来< /代码> 14
#include <future>

void function()
{
    // do asynchronous stuff.
}

int main()
{
    std::future<void> fut = std::async(std::launch::async, function);

    // do other stuff

    fut.get(); // synchronize threads
}