BOOST threading: cout behavior

I'm new to Boost threading, and I am fixated on how output is executed from multiple threads. I have a simple boost :: thread counting from 9 to 1; the main thread waits and then prints "LiftOff .. !!"

#include <iostream>
#include <boost/thread.hpp>
using namespace std;

struct callable {
    void operator() ();
};

void callable::operator() () {
    int i = 10;
    while(--i > 0) {
        cout << "#" << i << ", ";
        boost::this_thread::yield();
    }
    cout.flush();
}

int main() {
    callable x;
    boost::thread myThread(x);

    myThread.join();

    cout << "LiftOff..!!" << endl;

    return 0;
}

The problem is that I have to use the explicit cout.flush () operator in my stream to output the output. If I do not use flush (), I get only "LiftOff !!". as a way out.

Can someone please advise why I need to use flush () explicitly?

+5
source share
4 answers

, cout , - - flush, .

- , .

, , , - , . , , .

+5

, -, cout-. , cout , flush() . , , endl flush(), endl .

, ostream, , , . , .

+3

, , - . ( , std::endl << '\n' << std::flush.)

0

(gcc 4.3.2 boost 1.47 Linux RH5)

I assume that your cygwin system decides to implement several objects std::coutwith related ones std::streambuf. I assume this is a specific implementation. Since flusheither endl only causes its buffer to be painted over in its OS-controlled output sequence, the cout object of your stream remains buffered.

Sharing a link ostreambetween threads should solve the problem.

0
source

All Articles