Pre C++11, it depends on the implementation; at least one
implementation guaranteed synchronization of the calls. (VC++
guarantees the synchronization of std::cout
, but not for other
iostream objects. g++ offers the same guarantees as C++11,
even in earlier versions of the compiler.) In C++11, it is
explicitly undefined behavior.
The general rule is simple: any modification of state of an
object in any thread requires all accesses to be synchronized.
And all >>
operators on std::istream
are considered to
modify its state.
More generally, for any particular stream, it is probably a good
policy to use it in only one thread. (There are exceptions,
such as logging streams, where the logging object ensures thread
safety.) This is especially true of input, since even when
synchronized externally, the sequencing of the operators will
generally be unspecified if they are in separate threads. So
even with synchronization, if your user inputs "ab"
, which
thread gets 'a'
and which gets 'b'
in your example would be
undetermined.
EDIT:
There seem to be special rules for the standard stream objects
(std::cin
, std::cout
, etc.). Concurrent access is
guaranteed not to produce a data race, at least in some cases.
It may still result in characters being mixed, i.e.: if you're
inputing int
(rather than a single character), and your user
inputs "123 89\n"
, there's a possibility that thread 1 will see
"1389\n"
, and thread 2 "2 "
, which won't give you coherent
results.
My global recommendation stands. I can't think of any realistic
case where the interleaving of characters wouldn't create
a problem. (Also, I don't think I've ever written code which
actually inputs from std::cin
; it's always from an
std::istream&
which might be std::cin
, or might be
a file.)
stdin
is somehow special, and that there is an actualmain thread
. Remember that in C++,std::cin
is't really that special. It's just anstd::istream&
. And you really can't restrict everyistream&
to the main thread.