Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
333 views
in Technique[技术] by (71.8m points)

c++ - Is cout synchronized/thread-safe?

In general I assume that streams are not synchronized, it is up to the user to do appropriate locking. However, do things like cout get special treatment in the standard library?

That is, if multiple threads are writing to cout can they corrupt the cout object? I understand that even if synchronized you'd still get randomly interleaved output, but is that interleaving guaranteed. That is, is it safe to use cout from multiple threads?

Is this vendor dependent? What does gcc do?


Important: Please provide some kind of reference for your answer if you say "yes" since I need some kind of proof of this.

My concern is also not about the underlying system calls, those are fine, but the streams add a layer of buffering on top.

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The C++03 standard does not say anything about it. When you have no guarantees about the thread-safety of something, you should treat it as not thread-safe.

Of particular interest here is the fact that cout is buffered. Even if the calls to write (or whatever it is that accomplishes that effect in that particular implementation) are guaranteed to be mutually exclusive, the buffer might be shared by the different threads. This will quickly lead to corruption of the internal state of the stream.

And even if access to the buffer is guaranteed to be thread-safe, what do you think will happen in this code?

// in one thread
cout << "The operation took " << result << " seconds.";

// in another thread
cout << "Hello world! Hello " << name << "!";

You probably want each line here to act in mutual exclusion. But how can an implementation guarantee that?

In C++11, we do have some guarantees. The FDIS says the following in §27.4.1 [iostream.objects.overview]:

Concurrent access to a synchronized (§27.5.3.4) standard iostream object’s formatted and unformatted input (§27.7.2.1) and output (§27.7.3.1) functions or a standard C stream by multiple threads shall not result in a data race (§1.10). [ Note: Users must still synchronize concurrent use of these objects and streams by multiple threads if they wish to avoid interleaved characters. — end note ]

So, you won't get corrupted streams, but you still need to synchronize them manually if you don't want the output to be garbage.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...