Quantcast
Channel: 'printf' vs. 'cout' in C++ - Stack Overflow
Viewing all articles
Browse latest Browse all 19

Answer by Apollo for 'printf' vs. 'cout' in C++

$
0
0

I'd like to point out that if you want to play with threads in C++, if you use cout you can get some interesting results.

Consider this code:

#include <string>#include <iostream>#include <thread>using namespace std;void task(int taskNum, string msg) {    for (int i = 0; i < 5; ++i) {        cout << "#"<< taskNum << ": "<< msg << endl;    }}int main() {    thread t1(task, 1, "AAA");    thread t2(task, 2, "BBB");    t1.join();    t2.join();    return 0;}// g++ ./thread.cpp -o thread.out -ansi -pedantic -pthread -std=c++0x

Now, the output comes all shuffled. It can yield different results too, try executing several times:

##12::  ABABAB##12::  ABABAB##12::  ABABAB##12::  ABABAB##12::  ABABAB

You can use printf to get it right, or you can use mutex.

#1: AAA#2: BBB#1: AAA#2: BBB#1: AAA#2: BBB#1: AAA#2: BBB#1: AAA#2: BBB

Have fun!


Viewing all articles
Browse latest Browse all 19

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>