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
volatilekeyword.or possible read , write value through
interlocked's methodsexchange,read?if surround
_doneread , write operationlock (_someobject), need useinterlockedor prevent caching?
edit 1
- if define
_donevolatile, callupdatemethod multiple threads. possible 2 threads enterifstatement before assign_donefalse?
yes, technically that's not
volatilekeyword does; has result side-effect, though - , uses ofvolatilefor side-effect; msdn documentation ofvolatilelists side-effect scenario (link) - guess actual original wording (about reordering instructions) confusing? maybe is official usage?there no
boolmethodsinterlocked; you'd need useintvalues0/1, that's prettyboolanyway - notethread.volatilereadworklockhas full fence; don't need additional constructs there,lockenough 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