Use printf() while tracing from multithreaded console applications.

2 06 2008

Usually most of our back end server applications might be multi-threaded console applications which contain several threads running simultaneously. Usually we do trace issues by printing strings to console screen by using cout or printf(). As a general practice, we usually stick upon cout because of our affinity towards C++. 🙂 But there is a great pitfall lies behind.

If you use cout, you can see the traces are shuffled and displayed only after certain interval. This is because, cout uses buffered output. So if you need real time tracing, use printf().

if you still want to use cout, then flush the streams by calling flush(). See the code snippt.

// Trace the message.
cout << _T( "Tracing from thread" );

// flush the buffer.

This difference may not be visible if you are running one thread at a time. If you have a number of threads and each one is busy in dumping traces, definitely you can see this. 😉

Targeted Audience – Intermediate.