I wrote a small generic implementation of a simple generic double buffer pattern, and I was wondering if it's actually thread safe or can be improved in any way.
Note: The specific part that I'm worrying about thread safety is the Swap()
function.
/// <summary>
/// Simple generic double buffer implementation class
/// </summary>
public class DoubleBuffer<T> where T : class
{
private T _current;
public DoubleBuffer(T current, T next)
{
_current = current;
Next = next;
}
/// <summary>
/// Next buffer waiting in line (no active usage should be here)
/// </summary>
public T Next { get; private set; }
/// <summary>
/// Currently active buffer (active usage should be here)
/// </summary>
public T Current
{
get { return _current; }
}
/// <summary>
/// Swaps between the buffers
/// </summary>
/// <returns>Returns the buffer previously used before the swap</returns>
public T Swap()
{
var swappedBuffer = _current;
Interlocked.Exchange(ref _current, Next);
Next = swappedBuffer;
return swappedBuffer;
}
}
current
andnext
once, inside the constructor, and then useSwap
many times to swap them? And multiple threads can callSwap
simultaneously? I suppose you can only have two active threads at a single time using this? tl;dr: use a simplelock
to swap these two variables, performance difference will be negligible, but you will get correctness, which is far more important. Also, exposingCurrent
andNext
andSwap
publicly doesn't seem like a good idea, I would rethink how you want this class to be used. – Groo 16 hours agoTryEnter
with timeout is unnecessary, swapping these properties only takes a couple of instructions. – Groo 12 hours ago