multithreading - How to write thread-safe C# code for Unity3D? -


i'd understand how write thread safe code.

for example have code in game:

bool _done = false; thread _thread;  // main game update loop update() {     // if computation done handle start again     if(_done)     {         // .. handle ...         _done = false;         _thread = new thread(work);         _thread.start();     } }  void work() {      // ... massive computation       _done = true; } 

if understand correctly, may happened main game thread , _thread can have own cached version of _done, , 1 thread may never see _done changed in thread?

and if may, how solve it?

  1. is possible solve by, applying volatile keyword.

  2. or possible read , write value through interlocked's methods exchange , read?

  3. if surround _done read , write operation lock (_someobject), need use interlocked or prevent caching?

edit 1

  1. if define _done volatile , call update method multiple threads. possible 2 threads enter if statement before assign _done false?

  1. yes, technically that's not volatile keyword does; has result side-effect, though - , uses of volatile for side-effect; msdn documentation of volatile lists side-effect scenario (link) - guess actual original wording (about reordering instructions) confusing? maybe is official usage?

  2. there no bool methods interlocked; you'd need use int values 0/1, that's pretty bool anyway - note thread.volatileread work

  3. lock has full fence; don't need additional constructs there, lock enough jit understand need

personally, i'd use volatile. you've conveniently listed 1/2/3 in increasing overhead order. volatile cheapest option here.


Comments

Popular posts from this blog

Command prompt result in label. Python 2.7 -

javascript - How do I use URL parameters to change link href on page? -

amazon web services - AWS Route53 Trying To Get Site To Resolve To www -