I know that we will never see something like this
aabbABABaabb
as the output of the following code
Thread1
std::cout << "aa";
Thread2
std::cout << "bb";
By the way, will the writes be atomic if we add an endline to the previous calls like this?
Thread1
std::cout << "aa" << std::endl;
Thread2
std::cout << "bb" << std::endl;
Anyway, the single writes are atomic. So my question. Will it always hold that if thread1 requested a write before thread2, then we will see message "aa" before "bb"? If we know this always holds, it makes sense to log entries about the state of a multi-threaded application to be able to examine deadlocks and etc.
Other words, is it possible that Thread1 calls cout
first, but the actual message it requested to appear in the stream appeared only after Thread2 got its version of writing to stream executed. To me, this scenario is quite possible, if, for example, right after cout
was called, but actually before it was completely executed,there happened a context switch, and Thread2 was given enough time for both requesting cout
and having low-level os-dependent library actually execute Thread2's request. Correct me please if I am wrong and this scenario is not possible