Skip to content

Instantly share code, notes, and snippets.

@SamWindell
SamWindell / atomic_ref_list.h
Created March 16, 2024 14:14
Atomic linked list of reference counted objects - single reader, singler writer
// Single reader, single writer. Reading speed is the priority. Designed for the case where a
// background-thread is creating expensive-to-construct objects (like file reading + decoding) and a reading
// thread (such as a GUI thread) needs to use the objects with little overhead. The writing thread needs to
// frequently add or remove items from the list. Nodes from this struct can be stored in other data structures
// such as hash tables if needed. So long as node values are accessed with TryRetain and Release.
template <typename ValueType>
struct AtomicRefList {
// Nodes are never destroyed or freed until this class is destroyed so use-after-free is not an issue. To
// get around the issues of using-after-destructor, we use weak reference counting involving a bit flag.
struct Node {