HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpModerate

Simple generic double buffer pattern

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
genericsimpledoublepatternbuffer

Problem

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.

/// 
///     Simple generic double buffer implementation class
/// 
public class DoubleBuffer where T : class
{
    private T _current;

    public DoubleBuffer(T current, T next)
    {
        _current = current;
        Next = next;
    }

    /// 
    ///     Next buffer waiting in line (no active usage should be here)
    /// 
    public T Next { get; private set; }

    /// 
    ///     Currently active buffer (active usage should be here)
    /// 
    public T Current
    {
        get { return _current; }
    }

    /// 
    ///     Swaps between the buffers
    /// 
    /// Returns the buffer previously used before the swap
    public T Swap()
    {
        var swappedBuffer = _current;
        Interlocked.Exchange(ref _current, Next);
        Next = swappedBuffer;
        return swappedBuffer;
    }
}

Solution

Please correct me if I am wrong, but isn't such scenario possible with accepted answer?

public T Swap()
{
    var swappedBuffer = Interlocked.Exchange(ref _current, Next); // 1
    Next = swappedBuffer; // 2
    return swappedBuffer; // 3
}


And it goes like that: (A and B denotes some object of type T):

_current = A
Next = B

Thread 1 executes Line 1: 
swappedBuffer = A
_current = B
Next = B

Thread 2 executes Line 1:
swappedBuffer = B
_current = B
Next = B

Thread 1 executes Line 2:
Next = A

Thread 2 executes Line 2:
Next = B


Now both _current and Next are references to B.

Code Snippets

public T Swap()
{
    var swappedBuffer = Interlocked.Exchange(ref _current, Next); // 1
    Next = swappedBuffer; // 2
    return swappedBuffer; // 3
}
_current = A
Next = B

Thread 1 executes Line 1: 
swappedBuffer = A
_current = B
Next = B

Thread 2 executes Line 1:
swappedBuffer = B
_current = B
Next = B

Thread 1 executes Line 2:
Next = A

Thread 2 executes Line 2:
Next = B

Context

StackExchange Code Review Q#108763, answer score: 12

Revisions (0)

No revisions yet.