June 2017
Intermediate to advanced
532 pages
12h 59m
English
Ok, we've built this "cout wrapper" that automatically serializes concurrent printing attempts. How does it work?
Let's do the same steps our pcout helper does in a manual manner without any magic. First, it instantiates a string stream and accepts the input we feed into it:
stringstream ss;ss << "This is some printed line " << 123 << '\n';
Then it locks a globally available mutex:
{ lock_guard<mutex> l {cout_mutex};
In this locked scope, it accesses the content of string stream ss, prints it, and releases the mutex again by leaving the scope. The cout.flush() line tells the stream object to print to the terminal immediately. Without this line, a program might run faster because multiple printed lines can be bunched up ...
Read now
Unlock full access