Counting Owners in the Pencil Drawer
My collection has two pencils that take 0.5 mm lead, and one tube of HB refills between them. I could give each pencil its own tube, but sharing is tidier. The question is when that shared tube can leave the drawer.
Reference counting offers an answer: keep a tally of the owners, add one when an owner starts sharing, and subtract one when it stops. When the count reaches zero, nobody needs the shared item. This idea dates back to the early days of automatic memory management in the 1960s.
Here’s a small ledger in Lua. The pencils are represented by two calls to retain; the tube starts with no owners.
local tube = {lead = "0.5 mm HB", refs = 0}
local function retain(t)
t.refs = t.refs + 1
end
local function release(t)
t.refs = t.refs - 1
if t.refs == 0 then print("Release " .. t.lead) end
end
retain(tube)
retain(tube)
release(tube)
release(tube)
The C version keeps the same ledger, with a struct for the tube and functions that receive its address:
#include <stdio.h>
typedef struct { const char *lead; int refs; } Tube;
void retain(Tube *t) { t->refs++; }
void release(Tube *t) {
if (--t->refs == 0) printf("Release %s\n", t->lead);
}
int main(void) {
Tube tube = {"0.5 mm HB", 0};
retain(&tube);
retain(&tube);
release(&tube);
release(&tube);
return 0;
}
Both print Release 0.5 mm HB once, after the second pencil gives up its claim. These examples only print a message: Lua manages the table’s memory itself, and the C struct lives until main returns. A real ownership system must pair every retain with a release and must not use an object after it has been freed.
The tally has a blind spot, too. If two objects hold references to each other after everyone else lets go, their counts can stay above zero. Reference counting makes the ordinary case easy to follow; cycles need another strategy.