Note that there are some explanatory texts on larger screens.

plurals
  1. POBoost Threads - Racing
    text
    copied!<p>I'm playing around with some Boost threads, and I've written the following code:</p> <pre><code>#include &lt;boost/thread.hpp&gt; #include &lt;iostream&gt; 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 &lt; iterations; i++) { k++; output[k] = '0'; } } void y() { threads++; for (int i = 0; i &lt; iterations; i++) { k++; output[k] = '1'; } } int main(int argc, char* argv[]) { boost::thread a(&amp;w); boost::thread b(&amp;w); boost::thread c(&amp;y); boost::thread d(&amp;y); while (k &lt;= iterations * 4) {} for (int i=0; i &lt; k; i++) { std::cout &lt;&lt; output[i]; } return 0; } </code></pre> <p>What I don't understand is why the completion of these threads appeared to wait on each other, this is shown in the output:</p> <pre><code>000000000000000000000000000000000000000011111111 </code></pre> <p>I was under the impression the output would be in random order, with statements output similar to the following (expected output):</p> <pre><code>00100000111001000000010001111100000000011111111 </code></pre> <p>Instead they follow, all 0, then all 1 (or vice versa).</p> <p>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.</p> <p>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.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload