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?
is possible solve by, applying
volatile
keyword.or possible read , write value through
interlocked
's methodsexchange
,read
?if surround
_done
read , write operationlock (_someobject)
, need useinterlocked
or prevent caching?
edit 1
- if define
_done
volatile
, callupdate
method multiple threads. possible 2 threads enterif
statement before assign_done
false?
yes, technically that's not
volatile
keyword does; has result side-effect, though - , uses ofvolatile
for side-effect; msdn documentation ofvolatile
lists side-effect scenario (link) - guess actual original wording (about reordering instructions) confusing? maybe is official usage?there no
bool
methodsinterlocked
; you'd need useint
values0
/1
, that's prettybool
anyway - notethread.volatileread
worklock
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
Post a Comment