Click here to Skip to main content
15,886,611 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
When two thread trying to print some text on to the console using std::cout I'm getting some rubbish. How to achieve the synchronized access to std::cout?

T1:
C++
cout<<"Hello World"<<endl;

T2:
C++
cout<<"Hello Universe"<<endl;

I am getting the output something like:
Hello WHello Universe
orld

Any idea?
Posted
Updated 1-Feb-11 21:55pm
v2
Comments
Debojyoti Majumder 2-Feb-11 2:24am    
Can you share the code that creating the thread??

The simplest way: create a CriticalSection (is it Windows?) and write a separate output function, sandwich its body with EnterCriticalSection and LeaveCriticalSection; output to console only through this function.

Next time: please always indicate your platform in your question. Other detail may include code, exception dump with indication of code lines where exception is thrown, description of what the code does, the goal of application or a technique, etc.

—SA
 
Share this answer
 
v3
Comments
Olivier Levrey 2-Feb-11 3:47am    
I agree. If you are running under windows, then the "critical section" is what you are looking for.
Sergey Alexandrovich Kryukov 15-Jul-11 16:09pm    
Thank you, Olivier.
--SA
fjdiewornncalwe 2-Feb-11 14:36pm    
We have a winner... +5
Sergey Alexandrovich Kryukov 15-Jul-11 16:11pm    
Thank you, Marcus.
--SA
Espen Harlinn 2-Feb-11 16:22pm    
Good answer, a nice and simple solution - 5+
If what you are looking for is a flexible logging solution you should take a look at
ACE[^]

It provides a flexible distributed multi-thread aware logging solution, and a bunch of other features that's very useful if you into serious multi-threaded development.

Here is a nice little tutorial[^]

And here is a nice little list of serious projects using ACE and TAO[^]

Regards
Espen Harlinn
 
Share this answer
 
Comments
Sergey Alexandrovich Kryukov 2-Feb-11 20:26pm    
This is good stuff... my 5. Did you read "The Tao of Pooh" after Benjamin Hoff?
http://www.just-pooh.com/tao.html
--SA
How did you create the thread? I suspect you used CreateThread[^] and are using the single-threaded C-runtime library.

PS: Don't use CreateThread to create threads!
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900