...

/

Output streams with std::cout

Output streams with std::cout

Compare the difference between synchronized and non-synchronized access to std::cout.

🔑 Compiler support for synchronized output streams

At the end of 20202020, only GCC 11 supports synchronized output streams.

Non-synchronized access to std::cout

What happens when you write without synchronization to std::cout?

Press + to interact
#include <chrono>
#include <iostream>
#include <thread>
class Worker{
public:
Worker(std::string n):name(n) {};
void operator() (){
for (int i = 1; i <= 3; ++i) {
// begin work
std::this_thread::sleep_for(std::chrono::milliseconds(200));
// end work
std::cout << name << ": " << "Work " << i << " done !!!" << '\n';
}
}
private:
std::string name;
};
int main() {
std::cout << '\n';
std::cout << "Boss: Let's start working.\n\n";
std::thread herb= std::thread(Worker("Herb"));
std::thread andrei= std::thread(Worker(" Andrei"));
std::thread scott= std::thread(Worker(" Scott"));
std::thread bjarne= std::thread(Worker(" Bjarne"));
std::thread bart= std::thread(Worker(" Bart"));
std::thread jenne= std::thread(Worker(" Jenne"));
herb.join();
andrei.join();
scott.join();
bjarne.join();
bart.join();
jenne.join();
std::cout << "\n" << "Boss: Let's go home." << '\n';
std::cout << '\n';
}

The boss has six workers (lines 26 - 31). Each worker has to take care of three ...