✅ Can anyone give example code of using an Immutable Data Structure for Concurrency?
Can anyone give an example that shows how using these types are thread safe?
Interlocked.CompareExchange() methodInterlocked.CompareExchange(ref fieldOrVariable, newValue, oldValue) != oldValue would mean that the exchange was successfulint is immutable i use it as substitution for now and here would be an example implementation:Increment() at the same timeInterlocked.CompareExchange(ref _data, newData, oldData) call, and that is atomic and thread safe, no 2 threads can do this at the same time for the same refints, but ImmutableArray<int>s and instead of incrementing we are adding an element:newData = oldData + 1, u would build a new ImmutableArray<int> that contains both the elements of oldData and the element u want to addInterlocked.CompareExchange() is that it can not happen, this is on hardware level a compare-and-swap instructionInterlocked.CompareExchange<T>() requires T to be a class and immutable arrays are structs (so u need a a small wrapper)lock statement firstPrintAll()Data propertylock, Semaphore and what i explained at the beginning (Interlocked.CompareExchange()) are also about thread safety,lock, Semaphore and alike are pessimistic locks, they have some overhead under the hood, but that overhead is "stable" (doesnt spike much)Interlock.CompareExchange() is an optimistic lock, meaning that u have next to zero overhead for reading and writing with one thread, but quite some overhead when multiple threads want write access