I'm playing around with some Boost threads, and I've written the following code:
#include <boost/thread.hpp>
#include <iostream>
volatile int threads = 0;
const int iterations = 200;
volatile char output[iterations*4];
volatile int k = 0;
void w() {
threads++;
for (int i = 0; i < iterations; i++) {
k++;
output[k] = '0';
}
}
void y() {
threads++;
for (int i = 0; i < iterations; i++) {
k++;
output[k] = '1';
}
}
int main(int argc, char* argv[]) {
boost::thread a(&w);
boost::thread b(&w);
boost::thread c(&y);
boost::thread d(&y);
while (k <= iterations * 4) {}
for (int i=0; i < k; i++) {
std::cout << output[i];
}
return 0;
}
What I don't understand is why the completion of these threads appeared to wait on each other, this is shown in the output:
000000000000000000000000000000000000000011111111
I was under the impression the output would be in random order, with statements output similar to the following (expected output):
00100000111001000000010001111100000000011111111
Instead they follow, all 0, then all 1 (or vice versa).
Why is this? At this point it seems more like the threads are stacked in a random order, but still joined; ie waiting on each other before executing. I actually expected the threads++ code to possibly run at the same time in some threads, leaving them with the some thisthread value.
Disclaimer: I'm very new to Boost:threads, simply playing around, I understand race conditions are very dangerous (may lead to undefined behavior), this is just putting my hand in the fire so I can understand it.