1. 程式人生 > 實用技巧 >Peterson's Algothrim’演算法的Java實現和C++實現

Peterson's Algothrim’演算法的Java實現和C++實現

事實上Java實現並沒有成功,不知為何總會有似乎是死鎖的情況發生,任務並不能執行結束。

我已經再三檢查了我的程式碼實現,也邀請朋友來檢查我的程式碼,但朋友同樣也遇到了跟我一樣的問題。

Java實現:

 1 public class Solution{
 2 
 3     static int balance = 5000;      // 嘗試用兩個執行緒來對餘額進行修改
 4     static int trade_amount = 12;   // 一個執行緒充值,一個執行緒取錢,每次操作的額度和操作的次數相同
 5                                     // 在併發情況下,最後的金額應該還保持原來的數目
6 static boolean[] WhoIsRuning = new boolean[] {false, false}; 7 static int turn = 0; 8 9 public static void main(String[] args) throws InterruptedException { 10 long delay = 2; // 控制執行緒的速度,讓執行緒跑的慢一點 11 12 Thread one = new Thread(new Runnable(){ 13 @Override
14 public void run() { 15 int me = 0; 16 int other = 1; 17 for( int i = 0; i < 100; i++ ){ 18 /* 進入臨界區 */ 19 WhoIsRuning[me] = true; turn = other; 20 while( WhoIsRuning[other] && turn == other ) ;
21 /* 訪問敏感資源 */ 22 balance += trade_amount; 23 System.out.println("#" + i + " one(0) top up 13 yuan."); 24 /* 退出臨界區 */ 25 WhoIsRuning[me] = false; 26 /* 為了更容易觸發似乎是死鎖的情形,讓執行緒跑的慢一點*/ 27 try{ 28 Thread.sleep(delay); 29 }catch( InterruptedException e ){ 30 e.printStackTrace(); 31 } 32 } 33 } 34 }); 35 Thread another = new Thread(new Runnable(){ 36 @Override 37 public void run() { 38 /* 與執行緒1相似的程式碼,但改變了身份和行為 */ 39 int me = 1; 40 int other = 0; 41 42 for( int i = 0; i < 100; i++ ){ 43 WhoIsRuning[me] = true; turn = other; 44 while( WhoIsRuning[other] && turn == other ) ; 45 46 balance -= trade_amount; 47 System.out.println("#" + i + " another(1) withdraw up 13 yuan."); 48 49 WhoIsRuning[me] = false; 50 51 try{ 52 Thread.sleep(delay); 53 }catch( InterruptedException e ){ 54 e.printStackTrace(); 55 } 56 } 57 } 58 }); 59 one.start(); another.start(); 60 another.join(); one.join(); 61 62 System.out.println("\nthe balance now is " + balance); 63 } 64 }

C++實現得到了預期的效果:

// PetersonsAlgorithm.cpp : 此檔案包含 "main" 函式。程式執行將在此處開始並結束。
//

#include <iostream>
#include <thread>
#include <stdio.h>
#include <Windows.h>

int balance         = 5000;
int trade_amount    = 13;
int delay           = 0;

/* mutual exclusion contorls */ 
int wantsToAccessBalance[]  = { 0, 0 };
int turn                    = 0;

void TopUpBalance() {

    int me = 0, another = 1;
    for (size_t i = 0; i < 100; i++)
    {
        wantsToAccessBalance[me] = true; turn = another;
        while (wantsToAccessBalance[another] && turn == another);

        balance += trade_amount;
        printf("#%d. top up %d amount, the balance now left %d.\n",
            i, trade_amount, balance);
        Sleep(delay);
        wantsToAccessBalance[me] = false;
    }

}

void WithdrawMoney() {

    int me = 1, another = 0;
    for (size_t i = 0; i < 100; i++)
    {
        wantsToAccessBalance[me] = true; turn = another;
        while (wantsToAccessBalance[another] && turn == another);

        balance -= trade_amount;
        printf("#%d. withdraw %d amount, the balance now left %d.\n",
            i, trade_amount, balance);
        Sleep(delay);
        wantsToAccessBalance[me] = false;
    }
}

int main()
{
    std::thread     topup{ TopUpBalance };
    std::thread     withdraw{ WithdrawMoney };

    topup.join(); withdraw.join();

    printf("\nthe final balance now left %d.\n", balance);
}