Snaipe / libcsptr

Smart pointers for the (GNU) C programming language
https://snai.pe/c/c-smart-pointers/
MIT License
1.56k stars 141 forks source link

A comment on ref-counting #27

Open snej opened 1 year ago

snej commented 1 year ago

In the blog post you wrote:

lock-free implementations [of refcounting] rely on a compare-and-swap mechanism on the wrapped pointer – here, the pointer is not wrapped. This sucks, but if we make the assumption that no destruction shall happen during an async context, it’s kind of fine

This doesn’t make sense to me. I’ve implemented ref-counting a few times; it uses atomic increment/decrement of the refcount field, not the pointer to the object. When the decremented refcount hits zero you free the object, with no thread-safety issues because by definition only the current thread has a reference to it.

This assumes an “intrusive refcount” stored in the object's metadata. The C++ shared_ptr avoids that but it requires allocating a separate block containing the refcount and a pointer to the object, and the shared_ptr itself is a pointer to that block. That seems far too awkward to use in C since it required a double dereference.

acbits commented 3 months ago

I might be late to this, but I implemented ref-counting with compiler support. You may take a look here at https://github.com/acbits/reftrack-plugin