Does the Mutex mechanism comes into picture at the time of Console input/output in c/c++?
I mean, will the Console Stream be protected by Mutex and get locked/unlocked by threads in usual way?
Does the Mutex mechanism comes into picture at the time of Console input/output in c/c++?
I mean, will the Console Stream be protected by Mutex and get locked/unlocked by threads in usual way?
Yes wrapping output with a std::mutex
will make sure that separate threads don't access the stream at the same time. Individual calls to cout
when it is synchronized with stdio(default behavior) is safe although no guarantee is given on the order in which characters from multiple threads are inserted.
Consider
#include <iostream>
#include <mutex>
#include <thread>
std::mutex mx;
void print(char ch, int count)
{
std::lock_guard<std::mutex> lock(mx);
for (int i = 0; i < count; ++i)
{
std::cout << ch;
}
std::cout << std::endl;
}
int main() {
std::thread t1(print, 'x', 10);
std::thread t2(print, '*',20);
t1.join();
t2.join();
return 0;
}
With the mutex the output is(live example):
xxxxxxxxxx
********************
And without the mutex one possible output is(live example):
xxxxxxxxxx********************