int main()
{
int a = 0;
thread start(go);
thread mang(snd);
// ...
// wait for the threads to finish
start.join() ;
mang.join() ;
std::cout << "\ndone!\n" ;
}
Why are my results mixed? For instance, itll sometimes mix the numbers together but sometime the numbers will be spread out like this, 111111,22222,33333, when they should be like 12323112312231?
A thread could stop execution at any time, at any point during execution, and another thread could begin execution and print some of its letters, which would make the output look jumbled. There is no guarantee as to when threads will be executed, you're at the mercy of the CPU scheduler.
> Why are my results mixed? For instance, itll sometimes mix the numbers together
> but sometime the numbers will be spread out like this, 111111,22222,33333,
> when they should be like 12323112312231?
The stream buffers the output; std::cout << 1 ; is not an operation that would block.
To get the behaviour that you expect, put in a blocking call after a number is printed. For instance:
1 2
cout << 1 ;
std::this_thread::sleep_for(1ns) ; // sleep for at least one nano second
Thanks @JLBorges it works!
However i'd still like to try JawhawksZombie's solution as it intrigues me and feel like it'd be nice to learn, thanks to all!
For something like this, just making your thread sleep is fine. It isn't as complex as using a mutex.
I use mutexes to keep my threads from both trying to write to the same data/access the same data "at the same time". Let's say you had 2 (or more) threads accessing the SAME queue. You wouldn't want one pulling from the queue and the other pushing into the queue at the same time (trust me, you really don't).