2010-07-05 133 views
2

我需要實現從多線程調用的簡單函數。該功能的邏輯很簡單 - 想想賽馬 - 只有第一匹馬才能獲得金牌,一旦我們贏得比賽結束的贏家。如何實現簡單的多線程函數

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 我的意思是我的目標是不使用任何阻塞方法,如鎖定語句。

回答

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; 
} 
+0

他說,不使用鎖。 – Martin 2010-07-05 10:43:29

+1

太棒了!這正是我需要的一種非阻塞方法。 – 2010-07-05 10:44:15

+1

@Martin:他說沒有* lock語句*。他已經做的是(儘管是粗糙的)鎖。 – Mizipzor 2010-07-05 10:46:17

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); 
    } 
} 
+0

是的,但這是一個對於Monitor類所做的粗略近似。如果可以的話,我寧願相信BCL課程。特別是當涉及到並行時。 – 2010-07-05 11:31:37