justinstenning / SharedMemory

C# shared memory classes for sharing data between processes (Array, Buffer and Circular Buffer)
https://www.nuget.org/packages/SharedMemory
Other
566 stars 118 forks source link

Where to call AcquireWriteLock/AcquireReadLock #41

Closed vale1534 closed 5 years ago

vale1534 commented 5 years ago

In BufferWithLocks, any Write/Read memthod just call WriteWait/ReadWait to check that WriteWaitEvent/ReadWaitEvent is set, but not acqire locks, why?

Should I call AcquireWriteLock/AcquireReadLock in my userland code?

vale1534 commented 5 years ago
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.");
        }
justinstenning commented 5 years ago

@wenris depends on your code, if you need to asynchronously support read/write and want to ensure that the read waits for the write, then yes, manually call AcquireRead/WriteLocks at the appropriate times based on your logic (remember to release them also).

If you AcquireReadLock, then writing is blocked until your read lock is released. If AcquireWriteLock then reading is blocked until you release it.

It is left up to user land code because there are times you may need to write to the buffer multiple times before reading etc...

vale1534 commented 5 years ago

Is SharedArray/CircularArray thread-safe? @spazzarama

justinstenning commented 5 years ago

CircularBuffer is thread-safe, no locks required - it internally manages the circular buffer in such a way it is impossible to write over a node while reading it.

SharedArray is thread-safe if you use the AcquireRead/WriteLocks and ReleaseRead/WriteLocks around the read/writes. You can read and write to different indexes without locks if that suits the implementation. If you want an implementation that automatically acquires and releases locks upon read/write (and you only need a single read/write at a time), then simply create a class inheriting from SharedArray and override the Read/Write to acquire and release the appropriate locks around a call to the original Read/Write methods.