Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>False sharing between threads is when 2 or more threads use the same cache line.</p> <p>E.g. :</p> <pre><code>struct Work { Work( int&amp; d) : data( d ) {} void operator()() { ++data; } int&amp; data; }; int main() { int false_sharing[10] = { 0 }; boost::thread_group threads; for (int i = 0; i &lt; 10; ++i) threads.create_thread(Work(false_sharing[i])); threads.join_all(); int no_false_sharing[10 * CACHELINE_SIZE_INTS] = { 0 }; for (int i = 0; i &lt; 10; ++i) threads.create_thread(Work(no_false_sharing[i * CACHELINE_SIZE_INTS])); threads.join_all(); } </code></pre> <p>The threads in the first block do suffer from false sharing. The threads in the second block do not (thanks to <code>CACHELINE_SIZE</code>).</p> <p>Data on the stack is always 'far' away from other threads. (E.g. under windows, at least a couple of pages).</p> <p>With your definition of a function object, false sharing can appear, because the instances of <code>Work</code> get created on the heap and this heap space is used inside the thread.</p> <p>This may lead to several <code>Work</code> instances to be adjacent and so may incur sharing of cache lines.</p> <p>But ... your sample does not make sense, because data is never touched outside and so false sharing is induced needlessly.</p> <p>The easiest way, to prevent problems like this, is to copy your 'shared' data locally on tho the stack, and then work on the stack copy. When your work is finished copy it back to the output var.</p> <p>E.g: </p> <pre><code>struct Work { Work( int&amp; d) : data( d ) {} void operator()() { int tmp = data; for( int i = 0; i &lt; lengthy_op; ++i ) ++tmp; data = tmp; } int&amp; data; }; </code></pre> <p>This prevents all problems with sharing.</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