RSS Feed
Download our iPhone app
Browse DevX
Sign up for e-mail newsletters from DevX

Tip of the Day
Language: C++
Expertise: Intermediate
Feb 27, 2008

Multi-Threading: When printf Can Be Better than cout

If you use cout (or some other ostream) to output text data in a multi-threaded program, you'll probably get a lot of gibberish. One thread begins streaming text out, gets preempted, and then another thread starts streaming: a single line of text might contain characters from multiple threads.

That's not easy to decipher.

You could use a mutex to synchronize access to the ostream, but it's easier (and quicker!) to go back to the old C standards: printf and fprintf. These are more closely linked to the underlying write() calls; thus the thread is much less likely to be preempted in the middle of streaming data.

John Hendrix
Close Icon
Thanks for your registration, follow us on our social networks to keep up-to-date