Re: atomic counter
On 2011-10-09 12:27:42 +0000, Marc said:
I am trying to make our reference counting implementation thread-safe
(for a very basic definition of thread-safe), which essentially means
making the counter atomic. However, there are many options to atomic
operations, in particular concerning the memory model, and I want to
make sure I get it right.
The operations I use are increment (no return), decrement (and check
if the return value is 0), store (to initialize) and load (to check if
the object is not shared and thus safe to write into).
It looks to me like memory_order_relaxed should be good enough for
this purpose, as I don't see what synchronization would be needed with
the rest of memory, but I may be missing something fundamental there.
Suppose there are two references to the object, in two different
threads. One thread decrements the reference count, then the other
does. If the decrement from the first thread isn't seen by the second
thread, the second thread won't see that the count has become zero, and
the object won't get destroyed. So memory_order_relaxed won't work: you
need to ensure that the result of a decrement is visible to another
thread that also needs to decrement the count.
It's easier to get the code right when it's sequentially consistent. In
general, unless you can demonstrate that synchronization is a
bottleneck, don't mess with it.
--
Pete
Roundhouse Consulting, Ltd. (www.versatilecoding.com) Author of "The
Standard C++ Library Extensions: a Tutorial and Reference
(www.petebecker.com/tr1book)
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]