I would like to learn more about the exact behavior of a certain problem so That I can decide whether to use lock
(with its Performance implications).
Given the following pseudo code:
class Thread1
{
public decimal TotalValue {get; private set;}
private decimal StockAmount;
private decimal OldPrice;
public async Task GetStockPrices(string fictionalAsset)
{
while (true)
{
decimal totalCopy = TotalValue;
totalCopy -= (StockAmount * OldPrice);
OldPrice = StockPrices.GetValue(fictionalAsset);
totalCopy += (StockAmount * OldPrice);
TotalValue = totalCopy;
}
}
}
Let's assume, that Thread1
is the only Thread ever modifying TotalValue
. All other Threads (no matter their count) will only ever be reading from it.
For sure, it could happen that a reading Thread accesses TotalValue
while TotalValue = totalCopy;
.
What are the implications of it? Will the reading Thread "just" receive an old version of TotalValue
(OK) or could there be another unwanted result (such as 0 or any other number - FATAL). Are there other implications such as performance. Or time for update on other threads?
I would expect the above code to be more performant than
lock (TotalLock)
{
TotalValue = totalCopy;
}
especially since reading threads could be many and very frequently, effectively locking up the value.
In case Locking is required how are the locks served? (I would imagine fifo or random) - can there be a priority assigned for the writing thread? (something which checks if the variable is locked and if so, wait)