Sign in to follow this  

c++ iostreams thread safe ?

This topic is 3743 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

In C++, are the standard iostreams (std ::cout, std ::cerr, ...) thread safe ? Meaning that multiple threads may output things to these streams simultaneously without corrupting their internal state, or do I need to serialize their access? For example could the following piece of code crash a program if run simultaneously by several threads ? std::cout << "bloub" << std::endl; Or is an output looking like the following the worst thing that can happen : bloubbloub bloub bbloolubub …

Share this post


Link to post
Share on other sites
No, the design isn't thread-safe by very nature of API.

For practical purposes, calling them from different threads should work, although it's not guaranteed by standard.

I'd assume that due to nature of underlying console API, each thing sent to these strings is printed atomically. So std::cout << "Hello World"; will print "Hello World", but std::cout << "Hello " << "World"; may get interrupted by another thread.

I construct the strings to emit in a thread-safe manner, then send them as a string (including newline) and haven't noticed any anomalies.

Share this post


Link to post
Share on other sites

This topic is 3743 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this