Login | Register   
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Language: C++
Expertise: Intermediate
Feb 26, 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
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap