Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>The main reason for observing the sequential filling of the output buffer is that you threads complete too soon. 200 iterations are not enough for the worker threads to be interrupted. Instead of printing output, I appended this to your <code>main()</code>:</p> <pre><code>int switches = 0; for (int i=1; i&lt;iterations*4; ++i) if (output[i] != output[i-1]) ++switches; std::cout &lt;&lt; "Switches = " &lt;&lt; switches &lt;&lt; "\n"; </code></pre> <p>and started increasing <code>iterations</code>. Indeed, at some point (around 10,000,000 on my box) thread switches became apparent. That immediately revealed another problem with your program: increments of <code>k</code> are not atomic. You've declared <code>k</code> as volatile which means the compiler won't cache its value in a register when repeatedly checking it, like you do in the empty loop in <code>main</code>. However, volatile doesn't at all guarantee atomic increments. What does this mean in practice is when actual thread switches occur, <code>k++</code> doesn't always increment and the <code>while (k&lt;iterations*4) {}</code> loop will never terminate. To increment <code>k</code> atomically you need yet another external library - <a href="https://stackoverflow.com/questions/1158374/portable-compare-and-swap-atomic-operations-c-c-library">here's a discussion on the topic on SO</a>. If you happen to be on Windows, it might be easier to use <a href="http://msdn.microsoft.com/en-us/library/ms683614%28v=vs.85%29.aspx" rel="nofollow noreferrer">InterlockedIncrement</a> directly. If you do those changes to your program, you'll see the result you are expecting.</p> <hr> <p>There's also a subtle buffer overflow of output. Since you are incrementing k before writing to output, you are writing to indexes from 1 to iterations*4 included. You either need to initialize k to -1 or add one more element to the array</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

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