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