scanf()、std::cin 在多线程环境中的行为如何?

2024-01-06

我想用一个例子来说明我的问题。

假设有一个数组N /*(N>>1)*/设置为运行此函数的线程:

void Process() {
    //Some thread safe processing which requires in-deterministic computation time

    unsigned char byte;
    std::cin >> byte;
}

一旦所有这些同时启动,会发生什么?如何处理并发 std::cin 访问?在控制台上操作的最终用户会看到/体验到什么?

编辑:我还想补充一件事。下面的代码是否足够安全,可以放弃仅在一个(可能是主)线程中使用 std:cin 的想法?

void Process() {
    //Some thread safe processing which requires in-deterministic computation time

    //Mutex lock
    unsigned char byte;
    std::cin >> byte;
    //Mutex unlock
}

我想说,如果没有互斥体,结果是不可预测的。

如果您使用互斥锁,一切都很好。这就是互斥体的用途。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

scanf()、std::cin 在多线程环境中的行为如何? 的相关文章

随机推荐