【发布时间】:2013-09-17 07:52:42
【问题描述】:
我想用一个例子来说明我的问题。
假设有一组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
}
【问题讨论】:
-
具体来说,你不应该在多线程环境中完全避免这些函数,而应该只从一个线程调用它们。
-
我知道这种用法处理的安全问题。我问这个的原因是为我实现为交叉编译的 C++ 的新 SIMD 编程语言确定语法规则(是否强制程序员在主线程中使用标准输入)。
-
@diegoperini:假设
stdin在某种程度上是特殊的,并且存在一个实际的main thread。请记住,在 C++ 中,std::cin并没有那么特别。这只是一个std::istream&。而且你真的不能将每个istream&都限制在主线程中。
标签: c++ multithreading concurrency