Pre C ++ 11, it depends on the implementation; at least one implementation guaranteed call synchronization. (VC ++ guarantees std::cout synchronization, but not for other iostream objects. G ++ offers the same guarantees as C ++ 11, even in earlier versions of the compiler.) In C ++ 11, this is clearly undefined.
The general rule is simple: any modification of the state of an object in any thread requires that all calls be synchronized. And all >> operators on std::istream are considered to change its state.
In general, for any given thread, it is probably good to use it in only one thread. (There are exceptions, such as logging flows, where the logging object provides security flow.) This is especially true for input, because even when synchronized from the outside, the sequence of statements will usually not be specified if they are in separate streams. So even with synchronization, if your user enters "ab" , which thread receives 'a' and which receives 'b' in your example will be undefined.
EDIT:
There seem to be special rules for standard stream objects ( std::cin , std::cout , etc.). Parallel access is guaranteed not to race data, at least in some cases. This can lead to confusion of characters, i.e. If you enter int (and not just one character) and your user inputs "123 89\n" , there is a chance that thread 1 will see "1389\n" and thread 2 "2 " , which will not give you consistent results.
My global recommendation is worth it. I cannot imagine any realistic case where alternating characters would not pose a problem. (Also, I don't think I ever wrote code that actually inputs from std::cin ; it is always from std::istream& , which may be std::cin , or may be a file.)
James kanze
source share