2010-09-15 44 views
2

可能重複:
Peterson algorithm in Java?最簡單可行的實施鎖在java中

我試圖用Java實現鎖(鎖接口)在彼得森方法的線路。什麼是最簡單的非重入式實現來保證互斥。

flag[0] = 0; 
flag[1] = 0; 
turn; 

P0: flag[0] = 1;       P1: flag[1] = 1; 
    turn = 1;         turn = 0; 
    while (flag[1] == 1 && turn == 1)   while (flag[0] == 1 && turn == 0) 
    {           { 
      // busy wait         // busy wait 
    }           }         
    // critical section       // critical section 
     ...          ... 
    // end of critical section     // end of critical section 
    flag[0] = 0;        flag[1] = 0; 

我正在使用上述算法(來自wiki)。它似乎沒有工作,因爲儘管使用了易失性標誌和變量變量,但我獲得了許多數據競賽。有什麼需要照顧的?

下面的代碼:

public class TestLock implements Lock { 

    private final long thread1ID; 
    private final long thread2ID; 
    private volatile AtomicIntegerArray flagArr = new AtomicIntegerArray(50); 
    private volatile long turn = 0; 
    private volatile long currentThreadID = 0; 

    public TestLock(Thread thread1, Thread thread2) {  
     thread1ID = t0.getId(); 
     thread2ID = t1.getId();   
     flagArr.set((int)thread1ID, 0); 
     flagArr.set((int)thread2ID, 0);  
    } 
    public void lock() {   
     currentThreadID = Thread.currentThread().getId(); 
     flagArr.set((int)Thread.currentThread().getId(), 1);    
     turn = next();   
     while(turn == next() && flagArr.get((int)next()) == 1) 
     { 
      System.out.println(Thread.currentThread().getId()+" waiting");    
     } 
     //critical section 
     System.out.println(Thread.currentThread().getId()+" executing"); 
     } 

    private long next() { 
     return Thread.currentThread().getId() == thread1ID ? thread2ID : thread1ID;  
    } 

    public void unlock() {  
     flagArr.set((int)Thread.currentThread().getId(), 0);  
    } 
} 
+0

在這個問題中可能的答案:http://stackoverflow.com/questions/2911915/peterson-algorithm-in-java – Mike 2010-09-15 01:52:26

+0

嗯,這段代碼似乎正在實現相關問題的答案中提到的一切。 – blitzkriegz 2010-09-15 02:41:50

回答

0

那麼,基於公認的答案this SO question的意見,一個問題是你不能使用boolean [],預計到細胞具有volatile語義。

如果您發佈了您的代碼,我們可能會提供更多建議。

+0

我已經更新了代碼。你可以看看。 – Deeju 2010-09-15 02:29:36