Difference with cout and printf while multithreading in c++ Difference with cout and printf while multithreading in c++ multithreading multithreading

Difference with cout and printf while multithreading in c++


printf("Guest %ld goes to the check-in receptionist.\n", my_rank);

When you use printf, your string is formatted into an internal buffer and then output to the console in a single operation ("Guest 2 waits for check-in.").

cout << "Guest " << guestNumber << " waits for check-in." << endl;

When you use cout, your string is output to the console in multiple parts - "Guest", followed by guestNumber, followed by " waits for check-in.", followed by endl. This is because each call to the << operator takes place as if it were a separate function call (it returns a reference to the same cout object for the next call to use).

So although writing to the console itself is thread-safe and atomic, in the cout case it's only atomic for each separate sub-string.

The solution if you don't want to use printf would be to a) use a semaphore or other locking mechanism, or b) format the text before printing it using stringstream, and then output it as a single string.


The same results are also found by me. Printf always works. I don't think there is any way to make cout "thread safe" unless you make a lock. If you have to use stream to deal with strings, consider the following code:

ss << "Hello World! Thread ID, " << tid << endl;printf("%s",ss.str().c_str());