Add typed shared-memory buffer example
Introduce a generic shared buffer with typed span access and timeout-based read/write waits. Update the sample to verify data shared between two buffer views.
This commit is contained in:
@@ -0,0 +1,65 @@
|
||||
using DotNext.IO.MemoryMappedFiles;
|
||||
using SharedMemory;
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
|
||||
namespace WriterApp;
|
||||
|
||||
/// <summary>
|
||||
/// A <see cref="SharedBuffer"/> that creates no events, so that the lifetime of the shared memory
|
||||
/// can be tested apart from the lifetime of named events. Compiled into the tests and the peer.
|
||||
/// </summary>
|
||||
public class SharedBuffer<T> : BufferReadWrite where T : struct
|
||||
{
|
||||
public SharedBuffer(string name, int length) : base(name, length * Unsafe.SizeOf<T>())
|
||||
{
|
||||
}
|
||||
public SharedBuffer(string name) : base(name)
|
||||
{
|
||||
}
|
||||
/// <summary>
|
||||
/// Prevents write operations from deadlocking by throwing a TimeoutException if the WriteWaitEvent is not available within <see cref="ReadWriteTimeout"/> milliseconds
|
||||
/// </summary>
|
||||
private void WriteWait()
|
||||
{
|
||||
if (!WriteWaitEvent.WaitOne(ReadWriteTimeout))
|
||||
throw new TimeoutException("The write operation timed out waiting for the write lock WaitEvent. Check your usage of AcquireWriteLock/ReleaseWriteLock and AcquireReadLock/ReleaseReadLock.");
|
||||
}
|
||||
public void Write(T[] array)
|
||||
{
|
||||
WriteWait();
|
||||
var span = DataSpan;
|
||||
array.AsSpan().CopyTo(span);
|
||||
}
|
||||
/// <summary>
|
||||
/// Prevents read operations from deadlocking by throwing a TimeoutException if the ReadWaitEvent is not available within <see cref="ReadWriteTimeout"/> milliseconds
|
||||
/// </summary>
|
||||
private void ReadWait()
|
||||
{
|
||||
if (!ReadWaitEvent.WaitOne(ReadWriteTimeout))
|
||||
throw new TimeoutException("The read operation timed out waiting for the read lock WaitEvent. Check your usage of AcquireWriteLock/ReleaseWriteLock and AcquireReadLock/ReleaseReadLock.");
|
||||
}
|
||||
public void Read(T[] array)
|
||||
{
|
||||
ReadWait();
|
||||
var span = DataSpan;
|
||||
span.CopyTo(array.AsSpan());
|
||||
}
|
||||
public Span<byte> ByteSpan
|
||||
{
|
||||
get
|
||||
{
|
||||
return Mmf.CreateDirectAccessor(BufferOffset, BufferSize).Bytes;
|
||||
}
|
||||
}
|
||||
public Span<T> DataSpan
|
||||
{
|
||||
get
|
||||
{
|
||||
var spanT = MemoryMarshal.Cast<byte, T>(ByteSpan);
|
||||
return spanT;
|
||||
}
|
||||
}
|
||||
public T First => DataSpan[0];
|
||||
}
|
||||
Reference in New Issue
Block a user