C# 如何实现简单的多线程函数
我需要实现从多个线程调用的简单函数。该功能的逻辑很简单——想想赛马——只有第一匹马才能获得金牌,一旦我们有了赢家,比赛就结束了C# 如何实现简单的多线程函数,c#,.net,multithreading,C#,.net,Multithreading,我需要实现从多个线程调用的简单函数。该功能的逻辑很简单——想想赛马——只有第一匹马才能获得金牌,一旦我们有了赢家,比赛就结束了 class ConditionalOrderGroup { private volatile bool _locked = false; private List<ConditionalOrder> _ConditionalOrderList = null; public bool LockGroup(Conditional
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检查并继续执行else,该怎么办。如何重写这段代码
不使用锁定语句
更新
我的意思是,我的目标不是使用任何阻塞方法,比如lock语句。您需要一个单独的私有对象,并使用:
使用类以线程安全的方式更改变量的值。扩展DecCyclone所说的interlocked,这正是您要做的:
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);
}
}
伟大的这正是我需要的一种非阻塞方法。@Martin:他说没有lock语句。他已经在做的是一个锁本身(虽然很粗糙)。@Martin:TryEnter是锁,如果你可以不阻塞的话。如果你要走这条路,你要把Try/Finally语句包装在锁成功案例中的所有内容上,并把Monitor.Exit(挂锁)放在Finally中。假设您曾经想要释放锁,这可能是一个公平的假设;)Monitor.Exit(),而不是Monitor.Leave(),是的,但这是Monitor类所做工作的粗略近似值。如果可以的话,我宁愿相信BCL班。特别是在并行性方面。
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;
}
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);
}
}