我不明白为什么它阻止/抛出,除非我在主线程中添加this_thread :: sleep_for(然后它不阻止,并且所有三个调用都被执行).
编译器是从命令行使用的cl.exe.
#include <future> #include <mutex> #include <iostream> #include <string> #include <thread> #include <chrono> std::mutex printMutex; void print(const std::string& s) { std::lock_guard<std::mutex> lg(printMutex); for (char c : s) { std::cout.put(c); } std::cout << std::endl; } int main() { auto f1 = std::async(std::launch::async,print,"Hello from thread 1"); auto f2 = std::async(std::launch::async,"Hello from thread 2"); // std::this_thread::sleep_for(std::chrono::seconds(1)); print(std::string("Hello from main")); }
解决方法
崩溃是因为主线程在其他两个线程完成之前退出(并开始清理).
因此,两个期货的简单延迟(sleep_for)或.get()或.wait()应该为您解决.所以修改后的主要可能看起来像
int main() { auto f1 = std::async(std::launch::async,"Hello from thread 2"); print(std::string("Hello from main")); f1.get(); f2.get(); }
喜欢明确的等待或超过定时的“睡眠”.
关于一致性的注意事项
有一个建议从Herb Sutter改变等待或阻止在未来共享状态从异步返回.这可能是MSVC行为的原因,可以被视为已经实施了该提案.我不知道最终结果是提案是或将其整合(或其一部分)到C 14中.至少w.r.t.阻止从异步返回的未来,它看起来像MSVC行为没有达到规范.
有趣的是,第30.6.8 / 5章中的措词改变了;
来自C11
a call to a waiting function on an asynchronous return object that shares the shared state created
by thisasync
call shall block until the associated thread has completed,as if joined
到C 14
a call to a waiting function on an asynchronous return object that shares the shared state created
by thisasync
call shall block until the associated thread has completed,as if joined,or else time
out
我不知道如何指定“超时”,我想象它是实现定义.