I need to implement simple function that is called from multiple threads. The logic of the function is simple – think of horse races – only the first horse can get golden medal once we have a winner the race is over.
class ConditionalOrderGroup
{
private volatile bool _locked = false;
private List<ConditionalOrder> _ConditionalOrderList = null;
public bool LockGroup(ConditionalOrder initiator)
{
// this is finishline - we need to let only the first one proceed
if (_locked)
return false;
else
{
_locked = true;
}
// this is what winner gets
foreach (ConditionalOrder order in _ConditionalOrderList)
{
\\ cancel other orders
}
return true;
}
}
I am not happy with
if (_locked)
return false;
else
{
_locked = true;
}
What if two orders can pass if check and proceed to else. How to rewrite this code
without using lock statement?
UPDATE
I mean my goal is not use any blocking method like lock statement.
You need a separate, private object and use the built-in locking: