In the LWN series about lockless algorithms, there is a lot of detail about the atomic primitives used in them, but apart from ringbuffers, linked lists and RCU, I actually didn't see any mention of higher level lockless algorithms. For single-producer, single-consumer queues and for linked lists, lockless algorithms are known and performant, but many others are either not that performant, or they come with severe restrictions. For example, RCU sounds great, but you have to worry about grace periods, and you should only use it when you read much more often than you modify.
The only bugs found by TSAN (as noted in another reply) were the one you found and two assert()s that didn't use atomics. Those two asserts could be a big problem if one ran a non-NDEBUG build in production.
So now this is TSAN- and Helgrind-clean.
Thanks for prompting me to do this extra work!
If you reference N twice and M zero times, why did you define M? Did you make a typo in the O() or is this intentional?
> Most threads only ever need to call thread_safe_var_get().
> reference count the data.
Does getting a new value automatically release a reference to the old one (so it's no longer safe to read)?
That was a typo. It should have read `O(N log(M))`.
> Does getting a new value automatically release a reference to the old one (so it's no longer safe to read)?
Correct. Every read (get) of the variable causes the previous value to no longer be safe to use in that thread.