I have an array, that represents an inventory, with nearly 50 elements (items: some costum objects) and I need a readerwritelock for it (okay, i think a simple lock would be enough too). It should support both reference changing and value changing.
As reading and writing to different position of the array is threadsafe (Proof) I want to ensure that multiple read/write operations on the same array position is also threadsafe.
I surely could create 50 readerwriterlocks, but I don't want that ;) Is there a way to archive this? (I know ConcurrentList/Dictionary/etc. but I want an array...)
Thanks
If you are replacing the references in the array, then this is already safe, since reference swaps are inherently atomic. So you can use:
var val = arr[index];
// now work with val
and
var newVal = ...
arr[index] = newVal;
perfectly safely, at least in terms of avoiding torn references. So one pragmatic option is to make the object immutable, and just employ the above. If you need to change the value, take a local copy, make a new version based from that, and then swap them. If lost updates are a problem, then Interlocked.CompareExchange
and a re-apply loop can be used very successfully (i.e. you keep reapplying your change until you "win"). This avoids the need for any locking.
If, however, you are mutating the individual objects, then the game changes. You could make the object internally thread-safe, but this is usually not pretty. You could have a single lock for all the objects. But if you want granular locking then you will need multiple locks.
My advice: make the object immutable and just use the atomic reference-swap trick.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With