Created
December 5, 2018 06:01
-
-
Save r1235613/fb448637ef1ca08ef1a53568cab8d942 to your computer and use it in GitHub Desktop.
Peterson算法
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
do_flag = [False, False] | |
turn = 0 | |
# 以上是Peterson’s Solution的結構 | |
exp = 0 # 共同存取的變數,預期他應該在執行完後等於20 | |
def pro_0(): # 程序0 | |
global do_flag, turn, exp | |
do_flag[0] = True | |
yield | |
if do_flag[1] and turn == 1: | |
yield # 允許在等待時運行另一個程序 | |
for i in range(10): | |
exp = exp + 1 | |
print("PO 正在跑") | |
return None | |
def pro_1(): # 程序1 | |
global do_flag, turn, exp | |
do_flag[1] = True | |
yield | |
if do_flag[0] and turn == 0: | |
yield # 允許在等待時運行另一個程序 | |
for i in range(10): | |
exp = exp + 1 | |
print("P1 正在跑") | |
return None | |
if __name__ == "__main__": | |
a = pro_0() | |
b = pro_1() | |
stack = [a, b] | |
while True: | |
for task in stack: | |
try: | |
next(task) | |
except StopIteration: | |
pass | |
print(exp) | |
if exp == 20: | |
break |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment