C程序意外地阻止/抛出
我正在C中学习互斥体,并在以下代码中出现问题(取自N. Josuttis的“C标准库”).
我不明白为什么它阻止/抛出,除非我在主线程中添加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")); } 解决方法
我认为您看到的是MSVC实现异步(与未来相结合)的一致性问题.我相信是
not conformant.我可以使用VS2013重现它,但无法重现gcc的问题.
崩溃是因为主线程在其他两个线程完成之前退出(并开始清理). 因此,两个期货的简单延迟(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
到C 14
我不知道如何指定“超时”,我想象它是实现定义. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |