✅ 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?
int is immutable i use it as substitution for now and here would be an example implementation:ints, but s and instead of incrementing we are adding an element:Interlocked.CompareExchange()Interlocked.CompareExchange()Interlocked.CompareExchange()Interlocked.CompareExchange(ref fieldOrVariable, newValue, oldValue) != oldValuedo {
oldValue = currentValue
newValue = computeNewValueFromOldValue(oldValue);
} while (exchange did not happen);Increment()Interlocked.CompareExchange(ref _data, newData, oldData)refImmutableArray<int>ImmutableArray<int>newData = oldData + 1oldDataInterlocked.CompareExchange<T>()TlocklocklockPrintAll()DataSemaphoreSemaphoreInterlock.CompareExchange()public class Counter
{
private volatile int _data;
public int Current => _data;
public void Increment()
{
int oldData;
int newData;
do
{
// get the value
oldData = _data;
// generate a new value
newData = oldData + 1;
} while (Interlocked.CompareExchange(ref _data, newData, oldData) != oldData);
}
}public class Elements
{
private readonly object _syncObj = new();
private volatile ImmutableList<int> _list;
public ImmutableList<int> Data => _list;
public void Add(int element)
{
lock(_syncObj)
{
_list = _list.Add(element);
}
}
}public void PrintAll()
{
lock (_syncObj)
{
Console.WriteLine($"Count: {Data.Count}");
foreach(var element in Data)
{
Console.WriteLine($"\t{element}");
}
}
}public void PrintAll()
{
ImmutableList<int> data;
lock (_syncObj)
{
data = Data;
}
Console.WriteLine($"Count: {data.Count}");
foreach(var element in data)
{
Console.WriteLine($"\t{element}");
}
}public class Elements
{
private readonly object _syncObj = new();
private readonly List<int> _list = new();
public void Add(int element)
{
lock(_syncObj)
{
_list.Add(element);
}
}
public List<int> Data
{
get {
lock(_syncObj)
{
return new(_list);
}
}
}
}