Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ReaderWriterLock for array

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

like image 850
hellow Avatar asked Feb 20 '23 12:02

hellow


1 Answers

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.

like image 50
Marc Gravell Avatar answered Feb 22 '23 00:02

Marc Gravell