Suppose I have a byte array, Private Data as Byte()
. This array is private within a class. The class provides public functions for reading and writing to Data
.
This class can be accessed by multiple threads, so I want to avoid a situation where reading from it and writing from it don't happen at the same time.
For now, I am using SyncLock to avoid issues. Can I put SyncLock Data
in just the write functions, or does it need to be in the read functions? Or, both?
I don't have a specific code example in mind. I am just curious if there is any benefit to locking for both read and write functions if the writing functions' SyncLock will make writing have exclusive access to it in the first place.
The main reason you would want to lock on reading a byte array is to avoid a "phantom read" or other non-repeatable read -- if a writer is partway through updating the array, a reader may see some old values and some new values, or an 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 takes a SyncLock
and loops over the array adding 1 to each element, a reader that does not SyncLock
may see weirdness like [2, 3, 4, 4, 5, 6] -- only threads that actually take the SyncLock
will receive any safety.