Function tbuffer

Threaded dynamic circular array.

auto tbuffer(A) (
  A arg


It is a wait-free single consumer-producer threaded version of the unthreaded circular array. It achieves high throughput as it does not use mutexes or the built-in synchronized keyword. It however loses the ability to directly add elements to the buffer, the producer should instead be taught on how to fill the buffer using function pointers & delegates.


arg The initiating data for the array. If it is immutable, it is copied into a mutable buffer. An empty buffer initiation can be achieved with the .init of any array type.


buffer!(Unqual!(ForeachType!A)[], true)


auto buf = tbuffer("Hello world!");
buffer!(char[], true) buf = "Hello world!";
buffer!(int[], true) buf = tbuffer([1,2,3,4,5]);
buffer!(ulong[], true) buf = tbuffer(cast(ulong[]) [1,2,3,4,5]);


  • The ~= -operator cannot be used in @nogc code, but it does not use the GC.


The threaded version of the buffer loses the ability to concat directly to the buffer. Instead you should teach the producer how to fill the buffer:

 alias T = char;

 auto buf = tbuffer(T[].init);
 enum source = buf.source;

 int i = 1;

// Teach the producer.
// This is a delegate as it accesses i.
 buf ~= (T[] arr)
	arr[0] = T.init;
	return i;

assert(buf.length == 0);

// Request data if available
 buf ~= source;