Add flag to check if currently doing GC

This commit is contained in:
2025-09-08 15:55:18 -07:00
parent 06d6faf350
commit b18b59eeb0
3 changed files with 64 additions and 12 deletions

View File

@ -26,7 +26,16 @@ bool held_refs_callback(void *a_raw, RefcountList **out, void *ignored) {
return true;
}
void destroy_callback(void *a_raw, void *ignored) {
struct ContextAndFlag {
const RefcountContext *ctx;
bool should_be_doing_gc;
};
void destroy_callback(void *a_raw, void *ctx_and_flag_raw) {
struct ContextAndFlag *ctx_and_flag = ctx_and_flag_raw;
if (ctx_and_flag->should_be_doing_gc) {
assert(refcount_context_is_doing_gc(ctx_and_flag->ctx));
}
A *a = a_raw;
counting_free(a->str);
counting_free(a);
@ -38,9 +47,13 @@ void reref_destructor(void *a, void *ctx_raw) {
}
int main(int argc, const char **argv) {
RefcountContext *c =
refcount_make_context(offsetof(A, refcount), held_refs_callback,
destroy_callback, NULL, &COUNTING_ALLOCATOR);
struct ContextAndFlag ctx_and_flag = {.should_be_doing_gc = false};
RefcountContext *c = refcount_make_context(
offsetof(A, refcount), held_refs_callback, destroy_callback,
&ctx_and_flag, &COUNTING_ALLOCATOR);
ctx_and_flag.ctx = c;
A static_a = {
.num = 0,
@ -127,7 +140,11 @@ int main(int argc, const char **argv) {
assert(refcount_context_garbage_collect(c) == 0);
assert(refcount_context_num_refs(c, a_with_destructor) == 1);
assert(refcount_context_remove_destructor(c, a_with_destructor, &key));
assert(!refcount_context_is_doing_gc(c));
ctx_and_flag.should_be_doing_gc = true;
assert(refcount_context_garbage_collect(c) == 26);
ctx_and_flag.should_be_doing_gc = false;
assert(!refcount_context_is_doing_gc(c));
a = make_a(c, 0, "a");