summaryrefslogtreecommitdiff
path: root/docs/application/gc.md
blob: 9364e12194bb6c84eea1b77cc2dcf27c5089deda (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# Garbage Collection

---

## Object Definition

```c
typedef struct _kpl_gc {
    POOL_HEADER(_kpl_gc);
    union {
        _Atomic int32_t ref_count;
        _Atomic bool mark;
    } method;
    kpl_any any;
    pthread_mutex_t mutex;
} kpl_gc;

static _Atomic size_t marked_threads;

static kpl_gc *old_gc_head, *gc_head, *gc_tail;
```

## Counting

`ref_count` starts at 1

Each assign increments the reference count, each time it goes out of scope the reference count is decreased

When `ref_count` hits 0, data is freed

## Tracing

1. Once triggered add a init task to the async queue
2. This task moves the `gc_head` to the `old_gc_head` and sets the `gc_wait` to off for each thread
3. Each thread will run down its queue queue marking found gc objects
3. Once all have run and `marked_threads == available_threads` add a mark and sweep task to the async queue
4. Async task goes down async queue and does final mark, then a sweep on the `old_gc_head` is done
5. What remains on the `old_gc_head` is added to the gc tail