C++ Threading Help

Soldato
Joined
7 Apr 2004
Posts
4,212
Hi,

I'm using boost.threads library for a project im working on, and Im having some problems designing a thread safe wrapper for std::cout. I have to do this because several of my threads need to use cout, and i need to avoid any clashes.

So, my solution is to make a dedicated singleton Output class which i think is the best thing to do? Something like this:

Code:
class Output {
private:
...
public:
      void WriteData(const std::string& data_string); //Mutex's/locking etc in here
};

Then, for all my other classes I pass a pointer to this Output class in their respective constructors, and set a local private pointer to point to the Output instance, so for every new class i would do:

Code:
Output output;
...
MyClass mc(&output); // sets a pointer (*out) inside MyClass
... // Inside a thread
mc.out->WriteData("Hello World");


Am i going along the correct lines here? Or am i over complicating things with all the pointers :confused: I basically just want to be able to use cout safely within a thread.

Thanks a lot for any tips,

Jack
 
That would work ok, as long as 'output' is never destroyed while a class still may want to use it through the pointer it holds. If this is tricky, consider maybe using boost::shared_ptr<Output>, which does ref counting.

Another possibility, which retains the convenience of using the << operator with cout is to write "lock cout" and "unlock cout" manipulators, so you can do something like

cout << lock_cout << "four times two is " << 4x2 << '\n' << unlock_cout;

(the problem here is if you forget the unlock_cout, you'll end up with deadlock somewhere!)
 
Back
Top Bottom