Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Here are some general approaches that can minimize the use of locks, assuming your algorithm has some particular exploitable features:</p> <ol> <li><p>When updating a single numeric variable, you can use non-blocking primitives such as CAS, atomic_increment, etc. They are usually much faster that a classic blocking critical section (lock, mutex).</p></li> <li><p>When a data structure is read by multiple threads, but only written by one or few threads, an obvious solution would be a read-write lock, instead of a full lock.</p></li> <li><p>Try to exploit fine grain locking. For example, instead of locking an entire data structure with a single lock, see if you can use multiple different locks to protect distinct sections of the data structure.</p></li> <li><p>If you're relying on the implicit memory fence effect of locks to ensure visibility of a single variable across threads, just use <code>volatile</code><sup>1</sup>, if available.</p></li> <li><p>Sometimes, using a conditional variable (and associated lock) is too slow in practice. In this case, a <code>volatile</code> busy spin is much more efficient.</p></li> </ol> <p>More good advice on this topic here: <a href="http://software.intel.com/en-us/articles/intel-guide-for-developing-multithreaded-applications/" rel="nofollow noreferrer">http://software.intel.com/en-us/articles/intel-guide-for-developing-multithreaded-applications/</a></p> <p>A nice read in another SO question: <a href="https://stackoverflow.com/questions/2528969/lock-free-multi-threading-is-for-real-threading-experts">Lock-free multi-threading is for real threading experts</a> (don't be scared by the title).</p> <p>And a recently discussed lock-free Java implementation of atomic_decrement: <a href="https://stackoverflow.com/questions/9044023/starvation-in-non-blocking-approaches/9044184#9044184">Starvation in non-blocking approaches</a></p> <hr> <p><sup>1</sup> The use of <code>volatile</code> here applies to languages such as Java where <code>volatile</code> has defined semantics in the memory model, but not to C or C++ where <code>volatile</code> preceded the introduction of the cross-thread memory model and doesn't integrate with it. Similar constructs are available in those languages, such as the various <a href="http://en.cppreference.com/w/cpp/atomic/memory_order" rel="nofollow noreferrer"><code>std::memory_order</code></a> specifiers in C++.</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