【发布时间】:2015-01-27 01:44:15
【问题描述】:
不知道这个话题是和 std::thread 库还是流有关。看看下面的例子:
#include <thread>
#include <iostream>
void read(){
int bar;
std::cout << "Enter an int: ";
std::cin >> bar;
}
void print(){
std::cout << "foo";
}
int main(){
std::thread rT(read);
std::thread pT(print);
rT.join();
pT.join();
return 0;
}
我不在乎它是否会在执行 read() 函数之前或之后打印“foo”字符串。困扰我的是这样一个事实,当它在执行 print() 函数之前要求输入时,它实际上会挂起执行。我必须单击“输入”或向 std::cin 提供一些数据才能看到“foo”字符串。您可以在下面看到该程序行为方式的三种可能场景:
1.
>> Enter an int: //here I've clicked enter
>> foo
>> 12 //here I've written "12" and clicked enter
//end of execution
2.
>> fooEnter an int: 12 //here I've written "12" and clicked enter
//end of execution
3.
>> Enter an int: 12 //here I've written "12" and clicked enter
>> foo
//end of execution
如您所见,有时我必须单击 Enter 才能看到“foo”字符串。在我看来,它应该每次都打印出来,因为它是在单独的线程中启动的。也许 std::cin 以某种方式阻塞了 std::cout?如果是,那我该怎么办?
【问题讨论】:
标签: c++ multithreading c++11 inputstream outputstream