   [C++] Is this multi-thread safe?
  I often see some code on website that does this in C++ULONG MyComObject::Release(){INTERLOCKED_DECREMENT(&ref);if (ref == 0){delete this;return 0;}return ref;}is this safe for a multi-threaded environment? I was thinking that the interlocked decrement only ensure that it is safe for that instruction, however the subsequent code: if (ref == 0) ... wouldn't be safe.   
  Have a look at this.   ;  i see, so am i right to say the solution is to actually use a temporary variable to store the return value from InterlockDecrement().e.g[/source]ULONG MyComObject::Release(){LONG tempRef = INTERLOCKED_DECREMENT(&ref;if (tempRef == 0){delete this;return 0;}return tempRef;}[/source]hence even when 2 thread call release at the same time, it won't be deleted twice or return the wrong ref count.I am not sure if the forum thread meant that, but that is what i gathered from read the post+replies.   ;  Yeah, I would have written:ULONG newRef = INTERLOCKED_DECREMENT(&ref);if (newRef == 0)delete this;return newRef;With the original code:Let's say ref is currently 2.Thread #1: INTERLOCKED_DECREMENT(&ref);ref is now 1.Thread #2: INTERLOCKED_DECREMENT(&ref);ref is now 0.Thread #2: if (ref == 0)this evaluates as trueThread #1: if (ref == 0)this also evaluates as trueThread #1: delete this;Object is deletedThread #2: delete this;oops! Double deletion crash!!This highlights why the return values of the Interlocked* functions are very useful ;)   ;  Thanks for the quick replies :)   ;  We actually fixed a bug with using the interlocked functions wrong in that way in a project I work on a year or two ago.So yes, any code you see that does it the way you first posted, please do try to inform the relevant people of the correct method. It's not just theoretically wrong, I've seen that it does not work correctly in practice either.   