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

a call to a waiting function on an asynchronous return object that shares the shared state created
by this async 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 this async call shall block until the associated thread has completed,as if joined,or else time
out

我不知道如何指定“超时”,我想象它是实现定义.

相关文章

本程序的编译和运行环境如下(如果有运行方面的问题欢迎在评...
水了一学期的院选修,万万没想到期末考试还有比较硬核的编程...
补充一下,先前文章末尾给出的下载链接的完整代码含有部分C&...
思路如标题所说采用模N取余法,难点是这个除法过程如何实现。...
本篇博客有更新!!!更新后效果图如下: 文章末尾的完整代码...
刚开始学习模块化程序设计时,估计大家都被形参和实参搞迷糊...