RFC: safe ref counting
Steven Schveighoffer
schveiguy at gmail.com
Sat May 2 02:27:10 UTC 2020
In trying to make iopipe @safe, I came to the realization that having
auto-managed items such as files and the like (std.io Files and Sockets
are non-copyable), you need to rely on some form of @safe reference
counting. Unfortunately std.typecons.RefCounted is not and cannot be
safe. This is because it allocates in the C heap, and deallocates
regardless of whether anyone has ever squirreled away a reference.
So I thought I'd make a refCounted struct that uses the GC [1]. The
concept is simple -- allocate the refCounted payload in a GC block, then
pin the block as a root. Once all references are gone, remove the root.
But the memory stays behind to keep things memory safe (if, for example,
you saved a pointer to it outside a reference count object). The memory
will be in an initial state, but not invalid.
This means that if you include it in e.g. an array or a class, then it
still should work correctly (the memory is guaranteed to be present, and
anything it points at).
Of course, you can have cycles that prevent it ever from being cleaned
up. But most of the time, this is for auto cleaning up stack items. So
maybe that's OK?
Let me know what you think. It sucks that we have no valid way to do
reference counting in safe code, because std.io and iopipe highly depend
on it.
-Steve
[1] https://github.com/schveiguy/iopipe/blob/makesafe/source/iopipe/refc.d
More information about the Digitalmars-d
mailing list