coutとprintfの違い



Difference Between Cout



今日、Linuxマルチスレッドプログラミングを学ぶと、奇妙な現象が現れました。読み取り/書き込みロックを使用してデータにアクセスして印刷する場合、マルチスレッドプログラミングのほとんどがc関数を使用するため、出力データが混乱する現象がありましたが、私はC ++に精通しているため、C ++ステートメントをCコード、特にC ++の出力ストリームcoutですが、上記の問題が発生します。後で、coutからprintfへのすべての出力をテストしました。機能、他のコードは変更されておらず、以前の問題は再実行後に表示されないため、次の結論が得られます。

The cout statement is not an atomic operation. Every time we add data to the output buffer, it will not be refreshed to the interface immediately. Generally, the data in the buffer will be output to the interface after cout.flush() (usually it is very This kind of situation rarely occurs, because it is usually single-threaded and there is no CPU execution right preemption, so it can generally be refreshed in time, but it is different when applied to multi-threading, we should pay attention!), you can find through the source code, wrap endl The buffer will be refreshed (endl is actually a function template, the flush() function will be called to refresh the buffer immediately after the carriage return in the function!), so the output stream is not refreshed in time in the multi-threaded environment, so output confusion occurs. Compared with cout, the printf() function is atomic operation, that is, after inputting the data, it will refresh the output stream in time when jumping to other threads, and update the data to the output interface! This is a place to pay attention! ! !