1

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?

Nadeem Bhati
  • 739
  • 1
  • 8
  • 13
  • 2
    Why not try it? Start two threads that do nothing except console output in a loop. If you get output from both threads, it's protected bya lock of some sort, perhaps a mutex. If you process crashes, there is is no lock. – Martin James Jul 09 '15 at 16:59
  • 3
    Is this what you are asking? http://stackoverflow.com/q/6374264/ – Nemo Jul 09 '15 at 17:27

1 Answers1

3

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********************
NathanOliver
  • 171,901
  • 28
  • 288
  • 402
  • 2
    it means by default the console stream wont be handled by mutex or locked/unlocked by the same thread ? – Nadeem Bhati Jul 09 '15 at 17:13
  • 1
    @NadeemBhati if the call to `cout` comes in between a `mutex.lock()` and mutex.unlock()` then they will print in the order the threads are executed. – NathanOliver Jul 09 '15 at 17:32