Tom*_*zyk 2 c++ multithreading inputstream outputstream c++11
我不知道这个主题是否与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;
}
Run Code Online (Sandbox Code Playgroud)
我不在乎它是否会在执行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
Run Code Online (Sandbox Code Playgroud)
如您所见,有时我必须单击Enter才能看到"foo"字符串.在我看来,它应该每次打印,因为它是在一个单独的线程中启动.也许std :: cin以某种方式阻止了std :: cout?如果是的话那我该怎么办?
这是完全正常的,std::cout默认情况下输出为缓冲.cout被绑定到cin,所以当你开始阅读cin或按输入cout缓冲器被刷新,出现在屏幕上.
可能发生的是第一个线程写入其输出,它被缓冲,然后等待输入,刷新输出缓冲区(所以你看到"Enter an int:")然后第二个线程写入其输出,但它位于缓冲区直到读取输入,当输出再次刷新时.
您可以通过手动刷新其缓冲区来强制第二个线程立即输出:
std::cout << "foo" << std::flush;
Run Code Online (Sandbox Code Playgroud)
这可能会导致"fooEnter an int:"或者"Enter an int:foo"您不需要在"foo"出现之前按Enter键.
| 归档时间: |
|
| 查看次数: |
139 次 |
| 最近记录: |