简体   繁体   English

std :: thread和std :: endl没有预期的输出

[英]std::thread and std::endl no expected output

I am trying out some examples from C++11 threads I see some surprising results. 我正在尝试从C++11 threads一些示例,但我看到了一些令人惊讶的结果。 With the following code 用下面的代码

#include <iostream>
#include <thread>

void hello() {
    std::cout << "Hello concurrent world " << std::endl;
}
void do_something() {
    std::cout << "[background_task] --> [ do_something ]" << std::endl;
}
void do_something_else() {
    std::cout << "[background_task] --> [ do_something_else ]" << std::endl;
}
class background_task {
public:
    void operator()() const     {       
        do_something();
        do_something_else();
    }
};

int main ( int argc, char **argv) {
    std::thread t(hello);
    background_task bt;
    std::thread fn_obj_th(bt);
    t.join();
    fn_obj_th.join();
}

output is as follows 输出如下

Hello concurrent world [background_task] --> [ do_something ]

[background_task] --> [ do_something_else ]
Press any key to continue . . .

If I replace std::cout << "Hello concurrent world " << std::endl; 如果我替换了std::cout << "Hello concurrent world " << std::endl; with std::cout << "Hello concurrent world \\n"; std::cout << "Hello concurrent world \\n";

Result is 结果是

Hello concurrent world
[background_task] --> [ do_something ]
[background_task] --> [ do_something_else ]

Why in case with std::endl I am not getting expected output. 为什么以std::endl我没有得到预期的输出。

This: 这个:

std::cout << "Hello concurrent world " << std::endl;

is two separate outputs. 是两个单独的输出。 While std::cout is thread-safe, that doesn't mean that two separate invocations of it is guaranteed to be atomic. 尽管std::cout是线程安全的,但这并不意味着它的两个单独的调用可以保证是原子的。 A single output is atomic, but not two. 单个输出是原子的,但不是两个。

If you want a particular expression to be guaranteed to be atomically output, then you need to add your own synchronization primitives on top of std::cout . 如果希望确保某个特定表达式能够自动输出,则需要在std::cout顶部添加自己的同步原语。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM