Skip to content

Instantly share code, notes, and snippets.

@r1235613
Created December 5, 2018 06:01
Show Gist options
  • Save r1235613/fb448637ef1ca08ef1a53568cab8d942 to your computer and use it in GitHub Desktop.
Save r1235613/fb448637ef1ca08ef1a53568cab8d942 to your computer and use it in GitHub Desktop.
Peterson算法
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