【问题标题】:Strange behaviour of the thread library线程库的奇怪行为
【发布时间】: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


    【解决方案1】:

    这是完全正常的,输出到std::cout 默认是缓冲的。 coutcin 绑定,因此当您开始从 cin 读取或按 Enter 键时,cout 缓冲区会被刷新并出现在屏幕上。

    可能发生的情况是第一个线程写入它的输出,它被缓冲,然后它等待输入,它刷新输出缓冲区(所以你看到"Enter an int:")然后第二个线程写入它的输出,但它位于缓冲区,直到输入被读取,当输出再次刷新时。

    您可以通过手动刷新其缓冲区来强制第二个线程立即输出:

     std::cout << "foo" << std::flush;
    

    这可能会导致"fooEnter an int:""Enter an int:foo",但您不需要在出现"foo" 之前按Enter。

    【讨论】:

    • std::endl 是另一种选择,因为这基本上是\n' + std::flush
    猜你喜欢
    • 2018-03-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-07
    • 2018-09-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多