乐闻世界logo
搜索文章和话题

Is cout synchronized/ thread - safe ?

1个答案

1

std::cout itself is not guaranteed to be thread-safe in the C++ standard library. This means that when multiple threads attempt to use std::cout for output simultaneously, its behavior may be undefined, potentially leading to data races and garbled output.

Specifically, std::cout is an instance of std::ostream used for standard output. In single-threaded programs, using std::cout is safe. However, in a multi-threaded environment, if multiple threads attempt to access std::cout without locking, it may result in interleaved output, or worse, crashes or data corruption.

Example

Consider the following example where two threads output to standard output simultaneously:

cpp
#include <iostream> #include <thread> void print(int num) { for (int i = 0; i < 5; ++i) { std::cout << "Output from thread " << num << ": " << i << '\n'; } } int main() { std::thread t1(print, 1); std::thread t2(print, 2); t1.join(); t2.join(); return 0; }

In this example, threads t1 and t2 run concurrently and output to std::cout. Because std::cout is not protected by a lock, the output may be interleaved, making it difficult to read or analyze.

Solution

To address this issue, you can use a mutex (std::mutex) to synchronize access to std::cout:

cpp
#include <iostream> #include <thread> #include <mutex> std::mutex cout_mutex; void print(int num) { for (int i = 0; i < 5; ++i) { std::lock_guard<std::mutex> lock(cout_mutex); std::cout << "Output from thread " << num << ": " << i << '\n'; } } int main() { std::thread t1(print, 1); std::thread t2(print, 2); t1.join(); t2.join(); return 0; }

In this improved version, we use std::lock_guard, which automatically locks and unlocks cout_mutex each time output is performed. This ensures that only one thread can execute the output operation at a time, thereby avoiding the problem of garbled output.

In summary, although std::cout is not thread-safe in a multi-threaded environment, we can manually implement synchronization using a mutex to maintain output consistency and correctness.

2024年8月1日 18:18 回复

你的答案