value: thread-safe reference counting foundation

Add an atomic reference count to the common value header and the
retain/release API, without changing any existing ownership behaviour
(containers still do not free their children, so nothing new is freed
and the suite stays green).

- CAT_VALUE_Value gains `_Atomic long refcnt`.
- cat_value_retain / cat_value_release use atomic RMW with acq_rel
  ordering; the last release calls vtable->destroy after an acquire
  fence.  cat_value_refcount and cat_value_make_immortal complete the
  API.
- every heap constructor sets refcnt = 1 (its creator's reference).
- singletons are immortal (refcnt = -1): the empty object and
  true/false, so they are never freed and need no locking.

This makes the COUNT safe to share across threads.  It does not make a
mutable object safe under concurrent writes.
This commit is contained in:
Minus committed 2026-11-17 22:12:31 +00:00
1 parent 920e672d29
commit 22b8de3040
16 files changed
+103 -4

No files matched your search

+50
View File
@@ -25,6 +25,56 @@
#include <stdlib.h>
#include <string.h>
/* ---- reference counting (thread-safe) -------------------------------
*
* The count lives in the common value header. retain/release use atomic
* read-modify-write with acquire/release ordering, so the object graph
* can be shared across threads safely. Destroying the object runs on
* whichever thread drops the last reference.
*
* A negative count marks an immortal value (a singleton, or a wrapper
* whose storage lives on the C stack); retain/release ignore it. */
void cat_value_retain(CAT_VALUE_Value *v)
{
if (v == NULL)
return;
if (atomic_load_explicit(&v->refcnt, memory_order_relaxed) < 0)
return;
atomic_fetch_add_explicit(&v->refcnt, 1, memory_order_relaxed);
}
void cat_value_release(CAT_VALUE_Value *v)
{
long prev;
if (v == NULL)
return;
prev = atomic_load_explicit(&v->refcnt, memory_order_relaxed);
if (prev < 0)
return;
if (atomic_fetch_sub_explicit(&v->refcnt, 1,
memory_order_acq_rel) == 1) {
/* Last reference: publish our writes, then destroy. */
atomic_thread_fence(memory_order_acquire);
if (v->vtable != NULL && v->vtable->destroy != NULL)
v->vtable->destroy(v);
}
}
long cat_value_refcount(CAT_VALUE_Value *v)
{
if (v == NULL)
return 0;
return atomic_load_explicit(&v->refcnt, memory_order_relaxed);
}
void cat_value_make_immortal(CAT_VALUE_Value *v)
{
if (v == NULL)
return;
atomic_store_explicit(&v->refcnt, -1, memory_order_relaxed);
}
const char *cat_value_type_name(CAT_VALUE_Value *v)
{
if (v == NULL || v->vtable == NULL || v->vtable->type_name == NULL)