微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

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

原文地址:https://www.jb51.cc/c/111880.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐