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.
cout.flush();


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.

Advertisements




Reduce iostream compilation dependency by using iosfwd

30 03 2008

Icon Description
For making our classes compatible with cin and cout, we usually over load << and >> operators. And if such classes are the part of our modules interface, the iostream header file should be added to the interface header of our module. It makes compilation overhead for the classes those use our exported class. Please see the following code block.

#include <iostream>

class IMyInterface
{
public:
    // Overloaded << operator.
    std::ostream& operator<<( std::ostream& os );
};

Icon How Can I Do It?
You can easily reduce the compile time dependency of iostream header by using iosfwd. It contains forward declaration of several template classes defined in iostream. Please check MSDN for more details. Don’t forget to include iostream in your cpp files, since iosfwd contains just forward declarations.

#include <iosfwd>

class IMyInterface
{
public:
    // Overloaded << operator.
    std::ostream& operator<<( std::ostream& os );
};