Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Firstly, threading is tricky ;-p</p> <p>Yes, despite all the rumours to the contrary, it <strong>is</strong> required to <em>either</em> use <code>lock</code> <em>or</em> <code>volatile</code> (but not both) when accessing a <code>bool</code> from multiple threads.</p> <p>For simple types and access such as an exit flag (<code>bool</code>), then <code>volatile</code> is sufficient - this ensures that threads don't cache the value in their registers (meaning: one of the threads never sees updates).</p> <p>For larger values (where atomicity is an issue), or where you want to synchronize a <em>sequence</em> of operations (a typical example being "if not exists and add" dictionary access), a <code>lock</code> is more versatile. This acts as a memory-barrier, so still gives you the thread safety, but provides other features such as pulse/wait. Note that you shouldn't use a <code>lock</code> on a value-type or a <code>string</code>; nor <code>Type</code> or <code>this</code>; the best option is to have your own locking object as a field (<code>readonly object syncLock = new object();</code>) and lock on this.</p> <p>For an example of how badly it breaks (i.e. looping forever) if you don't synchronize - <a href="https://stackoverflow.com/questions/458173/can-a-c-thread-really-cache-a-value-and-ignore-changes-to-that-value-on-other-th/458193#458193">see here</a>.</p> <p>To span multiple programs, an OS primitive like a <code>Mutex</code> or <code>*ResetEvent</code> may also be useful, but this is overkill for a single exe.</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