我需要实现从多个线程调用的简单函数。这个功能的逻辑很简单 - 想想赛马 - 一旦我们有一个胜利者,只有第一匹马才能获得金牌。
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;
}
}
我对
不满意if (_locked)
return false;
else
{
_locked = true;
}
如果两个订单可以通过,如果检查并继续其他,该怎么办?如何重写此代码 不使用锁语句?
UPDATE 我的意思是我的目标不是使用像lock语句这样的阻塞方法。
答案 0 :(得分:2)
您需要一个单独的私有对象并使用built-in locking:
private object padLock = new object(); // 1-to-1 with _ConditionalOrderList
if (Monitor.TryEnter(padLock))
{
try
{
// cancel other orders
return true;
}
finally
{
Monitor.Exit(padLock);
}
}
else
{
return false;
}
答案 1 :(得分:1)
使用Interlocked
类以线程安全的方式更改变量的值。
答案 2 :(得分:1)
扩展decyclone所说的关于互锁的内容,这正是你要做的:
const int LOCKED = 1;
const int UNLOCKED = 0;
volatile int lockState = UNLOCKED;
public bool Foo()
{
try
{
//locking
//compare exchange returns the value that was in lockState before the compareExchange operation, so from that you can determine if you grabbed the lock or not
//if it was locked before, then you know the lock is not yours
if (Interlocked.CompareExchange(ref lockState, UNLOCKED, LOCKED) == LOCKED)
return false;
//lock is yours, do whatever stuff you like here, including throw exceptions
}
finally
{
//unlocking
//because this is in finally this lock will be released even if something goes wrong with your code
Interlocked.Exchange(ref lockstate, UNLOCKED);
}
}