Ring

Lock-free FIFO rings

A ring is a first-in, first-out queue which any number of threads may push to and pull from concurrently, without locks and without system calls. Neither waiting nor stage switching is involved: an operation which cannot proceed, such as pulling from an empty ring, returns at once. The rings implement the scalable circular queue designed by Ruslan Nikolaev (paper).

libevl provides two kinds of rings:

  • a ring of indices, declared in <evl/ring.h>, carries integer values from 0 to its size minus one, each value being present at most once at any time, so that the ring can never be full. Such ring holds no pointer, so it can live in memory which several processes map at different addresses. A typical use is to manage a pool of slots in shared memory, with one ring of free slots and one ring of busy ones.

  • a ring of pointers, declared in <evl/ring_ptr.h>, carries any pointer value within a process. Pushing to a full ring fails.

Both kinds are header-only: a macro defines a ring type of a given size along with its operations as inline functions, so that the compiler can optimize them for this size. The size of a ring is 2^order entries. The number of threads which may access a ring concurrently must not exceed its size.

Note

The rings rely on C11 atomics, they are not available from C++.

Managing a pool of slots

Two rings of indices and a table of slots make a lock-free allocator for a fixed number of slots. The table has as many slots as each ring has entries, and an index in a ring stands for the slot at this index in the table. One ring holds the indices of the free slots, the other one holds the indices of the busy slots, which carry data waiting to be used.

A producer pulls the index of a free slot from the free_slots ring, fills the slot, then pushes its index to the busy_slots ring; a consumer pulls the index of a busy slot from the busy_slots ring, uses the slot, then pushes its index back to the free_slots ring. Each index is in one of the rings or held by one thread. free_slots 6 7 3 oldest index on the left producer holds 5 consumer holds 2 slots[] 0 1 2 3 4 5 6 7 0 4 1 oldest index on the right busy_slots dequeue enqueue 5 fill slot 5 dequeue use slot 2 enqueue 2 free slot busy slot held by a thread
  • At start, filling the ring of free slots puts every index into it, and the ring of busy slots is cleared.

  • A producer pulls an index from the ring of free slots, writes its data to the matching slot, then pushes the index to the ring of busy slots. If the ring of free slots is empty, all slots are in use: the producer may try again later.

  • A consumer pulls an index from the ring of busy slots, uses the data in the matching slot, then pushes the index back to the ring of free slots.

At any time, each index is either in one of the rings, or held by a single thread, so neither ring can ever hold more indices than it has entries. The payload a thread writes to a slot before pushing its index is visible to the thread which pulls this index, see publishing the payload safely. Since the rings and the table hold no pointer, all of them may live in memory which several processes map at different addresses.

#include <stdint.h>
#include <time.h>
#include <evl/ring.h>

DEFINE_EVL_RING(slot_ring, 6);	/* 64 indices. */

struct sample {
	struct timespec date;
	int32_t values[4];
};

struct shared_area {
	struct slot_ring free_slots;
	struct slot_ring busy_slots;
	struct sample slots[64];
};

void setup(struct shared_area *area)
{
	evl_fill_slot_ring(&area->free_slots);
	evl_clear_slot_ring(&area->busy_slots);
}

bool produce(struct shared_area *area, const struct sample *sample)
{
	unsigned int idx;

	if (!evl_dequeue_slot_ring(&area->free_slots, &idx))
		return false;	/* No free slot. */

	area->slots[idx] = *sample;
	evl_enqueue_slot_ring(&area->busy_slots, idx);

	return true;
}

bool consume(struct shared_area *area, struct sample *sample)
{
	unsigned int idx;

	if (!evl_dequeue_slot_ring(&area->busy_slots, &idx))
		return false;	/* Nothing to consume. */

	*sample = area->slots[idx];
	evl_enqueue_slot_ring(&area->free_slots, idx);

	return true;
}

Publishing the payload safely

On a multi-core system, a CPU may see the memory writes of another CPU in a different order than they were issued, and the compiler may reorder memory accesses too. A consumer could then pull an index or a pointer, and read a payload which is not complete yet, or no longer valid. Both kinds of rings prevent this for the payload they hand over, as long as pushing the index or the pointer is what publishes the payload:

The producer pulls index i, writes slot i, then pushes i to the busy ring with release semantics. The consumer pulls i from the busy ring with acquire semantics, so it sees what the producer wrote, reads slot i, then pushes i back to the free ring with release semantics. The next thread which pulls i from the free ring writes slot i only after these reads are done. No thread touches slot i once it pushed i. producer consumer pull i from free_slots acquire write payload to slot i push i to busy_slots release touch slot i never once i is pushed owns slot i pull i from busy_slots acquire read payload from slot i push i to free_slots release owns slot i writes before the push are seen after the pull pull i from free_slots acquire, next round reads before the push are done before the next write

Pushing an index has release semantics: every write the thread issued before, to the slot or to any other memory such as a buffer the slot points at, is visible to other CPUs before the index is. Pulling an index has acquire semantics: the reads and writes the thread issues after the pull cannot happen before it. Therefore, the consumer which pulls the index sees the whole payload, and only after it was published. The rule of thumb follows: a thread should access a slot and its payload only between pulling the index and pushing it, writing the payload completely before pushing. Once the index is pushed, the thread should not touch the slot anymore, not even to read it. Then no explicit barrier is needed, for threads of the same process as well as for threads of different processes sharing the memory.

The same applies to a ring of pointers, where the payload is the object a pointer refers to. Pushing and pulling a pointer have the same release and acquire semantics as pushing and pulling an index. The producer should write the object completely before pushing its pointer, and leave it alone afterwards. The consumer should access the object only after pulling its pointer.

If threads publish a payload by other means, such as a flag or a counter in shared memory, they need the same pair of barriers on their own. The producer sets the flag with atomic_store_explicit(&flag, 1, memory_order_release) once the payload is written. The consumer reads it with atomic_load_explicit(&flag, memory_order_acquire) before reading the payload. Each side needs its half of the pair, on the same variable: a release store without a matching acquire load orders nothing, and neither does a plain or volatile access to the flag: volatile only keeps the compiler from optimizing the access away, it is no memory barrier (see why “volatile” should not be used in the kernel documentation).

Progress guarantee

The rings implement the SCQ algorithm, which the paper proves to be lock-free, provided that no more threads access a ring concurrently than it has entries. Whatever the timing of the threads, at least one of them completes its operation in a finite number of steps. A thread preempted in the middle of an operation, for instance by a thread of higher priority on the same CPU, does not prevent the others from completing theirs, as it would if it held a lock. Lock-free does not mean wait-free though: under heavy contention, a particular thread may have to retry a few times before its own operation completes.

This guarantee covers the ring operations, not the loops built on top of them. A loop which retries pushing to a full ring, or pulling from an empty one, waits for another thread to pull or push. It can only end if that thread gets to run: a producer spinning on the CPU where a consumer of lower priority should run would wait forever. Such a loop should run on a CPU of its own, or sleep between attempts with evl_usleep(), or wait on a synchronization element which the other side signals, such as a semaphore.

Ring services

DEFINE_EVL_RINGDefine a ring type carrying indices, with its operations.
DEFINE_EVL_RING_STATICDefine a ring type carrying indices, plus an empty ring of this type.
SIZEOF_EVL_RINGSize of a ring carrying indices, for allocating it.
DEFINE_EVL_RINGPTRDefine a ring type carrying pointers, with its operations.
DEFINE_EVL_RINGPTR_STATICDefine a ring type carrying pointers, plus an empty ring of this type.
DEFINE_EVL_RINGPTR_DYNAMICDefine a ring type carrying pointers, plus an allocation routine.
DEFINE_EVL_RING(name, order)
#include <evl/ring.h>

Define the type struct name for a ring of 2^order indices, with the following operations:

  • void evl_enqueue_name(struct name *ring, unsigned int idx) pushes idx, which must be lower than 2^order and not already in the ring.

  • bool evl_dequeue_name(struct name *ring, unsigned int *pidx) pulls the oldest index into *pidx, returning false if the ring is empty.

  • void evl_clear_name(struct name *ring) empties the ring.

  • void evl_fill_name(struct name *ring) fills the ring with the indices from 0 to 2^order - 1.

Unlike pushing and pulling, clearing and filling are not safe against concurrent access to the ring: the caller must serialize them.

A ring of this type which lives in allocated or shared memory needs SIZEOF_EVL_RING(order) bytes, aligned on EVL_RING_ALIGNMENT. It must be initialized by evl_clear_name() or evl_fill_name() before use. A pool of slots is a typical use.

For instance, DEFINE_EVL_RING(foo, 4) expands to the following code. The operations are thin wrappers passing the order as a constant, so that the compiler can fold it into the generic code. The array has twice as many cells as the ring has entries, as the algorithm requires.

struct foo {
	struct __evl_ring_base base;	/* head, tail, threshold */
	__aligned(EVL_RING_CACHELINE_BYTES) _Atomic(lfatomic_t) array[32];
} __aligned(EVL_RING_ALIGNMENT);

static inline void evl_enqueue_foo(struct foo *ring, unsigned int idx)
{
	__evl_ring_enqueue((struct __evl_ring *)ring, 4, idx);
}

static inline bool evl_dequeue_foo(struct foo *ring, unsigned int *pidx)
{
	return __evl_ring_dequeue((struct __evl_ring *)ring, 4, pidx);
}

static inline void evl_clear_foo(struct foo *ring)
{
	__evl_ring_clear((struct __evl_ring *)ring, 4);
}

static inline void evl_fill_foo(struct foo *ring)
{
	__evl_ring_fill((struct __evl_ring *)ring, 4);
}
DEFINE_EVL_RING_STATIC(name, order)
#include <evl/ring.h>

The same as DEFINE_EVL_RING, also defining an empty ring of this type as a variable called name.

SIZEOF_EVL_RING(order)
#include <evl/ring.h>

The size in bytes of a ring of 2^order indices.

DEFINE_EVL_RINGPTR(name, order)
#include <evl/ring_ptr.h>

Define the type struct name for a ring of 2^order pointers, with the following operations:

  • void evl_init_cursor_name(struct evl_ring_cursor *cursor) initializes the cursor of a thread which pushes to the ring. Each such thread needs its own cursor, which saves it from reading the shared state of the ring on every push.

  • bool evl_enqueue_name(struct name *ring, void *ptr, struct evl_ring_cursor *cursor) pushes ptr, returning false if the ring is full.

  • bool evl_dequeue_name(struct name *ring, void **pptr) pulls the oldest pointer into *pptr, returning false if the ring is empty.

  • void evl_clear_name(struct name *ring) empties the ring. This operation is not safe against concurrent access to the ring: the caller must serialize it.

On some platforms, the pointer rings need the libatomic library for the double-width compare-and-swap operation.

Pushing a pointer publishes the object it refers to: the producer must write the object completely before, and not touch it afterwards, see publishing the payload safely.

For instance, DEFINE_EVL_RINGPTR(foo, 4) expands to the following code. Each cell of the array is twice as wide as a pointer, so that it can carry a pointer along with the state the algorithm keeps for this cell.

struct foo {
	struct __evl_ring_base base;	/* head, tail, threshold */
	__aligned(EVL_RING_CACHELINE_BYTES) _Atomic(lfatomic_big_t) array[32];
} __aligned(EVL_RING_ALIGNMENT);

static inline bool evl_enqueue_foo(struct foo *ring, void *ptr,
				struct evl_ring_cursor *cursor)
{
	return __evl_ringptr_enqueue((struct __evl_ringptr *)ring, 4, ptr, cursor);
}

static inline bool evl_dequeue_foo(struct foo *ring, void **pptr)
{
	return __evl_ringptr_dequeue((struct __evl_ringptr *)ring, 4, pptr);
}

static inline void evl_init_cursor_foo(struct evl_ring_cursor *cursor)
{
	cursor->head = 32;
}

static inline void evl_clear_foo(struct foo *ring)
{
	__evl_ringptr_clear((struct __evl_ringptr *)ring, 4);
}
#include <evl/ring_ptr.h>

DEFINE_EVL_RINGPTR_STATIC(requests, 8);	/* 256 pointers. */

void producer(void)
{
	struct evl_ring_cursor cursor;
	struct request *req;

	evl_init_cursor_requests(&cursor);
	for (;;) {
		req = get_request();
		while (!evl_enqueue_requests(&requests, req, &cursor))
			;	/* The ring is full, try again. */
	}
}

void consumer(void)
{
	void *req;

	for (;;) {
		if (evl_dequeue_requests(&requests, &req))
			handle_request(req);
	}
}

Both threads spin when the ring is full or empty, which is only safe under the conditions given in progress guarantee.

DEFINE_EVL_RINGPTR_STATIC(name, order)
#include <evl/ring_ptr.h>

The same as DEFINE_EVL_RINGPTR, also defining an empty ring of this type as a variable called name.

DEFINE_EVL_RINGPTR_DYNAMIC(name, order)
#include <evl/ring_ptr.h>

The same as DEFINE_EVL_RINGPTR, also defining struct name *evl_alloc_name(void), which allocates an empty ring of this type. A large ring is better allocated this way than defined statically. evl_alloc_name() returns NULL and sets errno on failure. The ring is released by free().


Last modified: Wed, 25 Nov 2026 16:53:53 +0100