c++ - Is this code thread-safe? -


let's have thread-safe compare-and-swap function like
long cas(long * dest ,long val ,long cmp)
compares dest , cmp, copies val dest if comparison succesful , returns original value of dest atomically.

so ask if code below thread-safe.

while(true) {     long dummy = *destvar;     if(dummy == cas(destvar,value,dummy) )      {         break;     }  } 

edit:
dest , val parameters pointers variables created on heap. interlockedcompareexchange example out cas function.

edit. edit question means of isn't relevant. still, i'll leave concerns in c# case carry c++ case, c++ case brings many more concerns stated, it's not entirely irrelevant.


yes, but...

assuming mean cas atomic (which case c# interlocked.compareexchange , things available use in c++ libraries) it's thread-safe in , of itself.

however destvar = value thread-safe in , of (it in c#, whether in c++ or not implementation dependent).

in c# write integer guaranteed atomic. such, doing destvar = value not fail due happening in thread. it's "thread-safe".

in c++ there no such guarantees, there on processors (in fact, let's drop c++ now, there's enough complexity when comes stronger guarantees of c#, , c++ has of complexities , more when comes these sort of issues).

now, use of atomic cas operations in "thead-safe", not complexity of thread safety comes in. it's thread-safety of combinations of operations important.

in code, @ each loop either value atomically over-written, or won't. in case won't it'll try again , keep going until does. end spinning while, work.

and in doing have same effect simple assignment - including possibility of messing what's happening in thread , causing serious thread-related bug.

take look, comparison, answer @ is use of static queue thread-safe? , explanation of how works. note in each case cas either allowed fail because failure means thread has done "useful" or when it's checked success more done stopping loop. it's combinations of cass each pay attention possible state caused other operations allow lock-free wait-free code thread-safe.

and we've done that, note couldn't port directly c++ (it depends on garbage collection make possible aba scenarios of little consequence, c++ there situations there memory leaks). matter language talking about.


Comments

Popular posts from this blog

asp.net - repeatedly call AddImageUrl(url) to assemble pdf document -

java - Android recognize cell phone with keyboard or not? -

iphone - How would you achieve a LED Scrolling effect? -