SyncLock on record? To read? Or both?

Suppose I have an array of bytes, Private Data as Byte() . This array is private within the class. The class provides public functions for reading and writing to Data .

This class can be accessed via several threads, so I want to avoid the situation when reading from and writing from it do not occur simultaneously.

I am currently using SyncLock to avoid problems. Can I put SyncLock Data only in write functions, or should it be in read functions? Or both?

I do not have a specific code example. I'm just wondering if there are any blocking benefits to the read and write functions if the "SyncLock" write functions make the recording primarily exclusive access to it.

+4
source share
2 answers

The main reason you want to block the reading of a byte array is to avoid "reading phantom" or other non-repeatable reading - if the author partially refreshes the array, the reader may see some old values โ€‹โ€‹and some new values, or the old value, and then the new value if it reads it again.

For example, if you have an array containing [1, 2, 3, 4, 5, 6] and a writer thread that accepts SyncLock and loops over the array, adding 1 to each element, a reader that SyncLock cannot see weirdness like [ 2, 3, 4, 4, 5, 6] - only threads that actually accept SyncLock will receive any security.

+3
source

Instead of using SyncLock, you should use ReaderWriterLockSlim (or ReaderWriterLock if you are not in .NET 4).

It is intended to allow a single writer, but several readers. This is usually ideal for a situation like the one you are describing.

Otherwise, you can use SyncLock, but you will need to block read and write operations. Without blocking on both, it is possible for your reader to read data while the writer is still writing, which will lead to reading semi-loaded data.

+4
source

Source: https://habr.com/ru/post/1334611/


All Articles