Peterson算法中为何不将turn变量设置为当前进程?
关于Peterson算法中turn变量设置的疑问
在Peterson算法中,进程会将turn变量设置为另一个进程。但我想知道为何我们不将turn变量设置为当前进程,示例代码如下:
void process0() { flag[0] = 1; // Process 0 wants to access the critical section turn = 0; // It's Process 0's turn to access the critical section while (flag[1] && turn == 1); // If Process 1 wants to access the critical section and it IS Process 1's turn, then Process 0 should wait // Process 0 accesses the critical section flag[0] = 0; // Process 0 quits the critical section // Remaining codes } void process1() { flag[1] = 1; // Process 1 wants to access the critical section turn = 1; // It's Process 1's turn to access the critical section while (flag[0] && turn == 0); // If Process 0 wants to access the critical section and it IS Process 0's turn, then Process 1 should wait // Process 1 accesses the critical section flag[1] = 0; // Process 1 quits the critical section // Remaining codes }
看起来始终有且仅有一个进程能进入临界区,那为何不将turn变量设为当前进程编号?
我用以下Python代码进行了测试:
import threading, random END_POSSIBILITY = 0.001 # The possibility that one process finishes running flag = [False, False] turn = 0 class CriticalSection: def __init__(self) -> None: self.visitor = -1 def visit(self, visitor: int) -> None: if self.visitor == -1: self.visitor = visitor else: raise Exception(f"CRITICAL SECTION IS ALREADY BEING VISITED BY PROCESS {self.visitor}, CANNOT BE VISITED BY {visitor}!!!") def unvisit(self) -> None: self.visitor = -1 critical_section = CriticalSection() def process0(): global turn while True: flag[0] = True turn = 0 while flag[1] and turn == 1: pass critical_section.visit(0) flag[0] = False critical_section.unvisit() if (random.random() <= END_POSSIBILITY): break def process1(): global turn while True: flag[1] = True turn = 1 while flag[0] and turn == 0: pass critical_section.visit(1) flag[1] = False critical_section.unvisit() if (random.random() <= END_POSSIBILITY): break thread0 = threading.Thread(target=process0) thread1 = threading.Thread(target=process1) thread0.start() thread1.start()
多次运行该代码后,一切均正常。
内容的提问来源于stack exchange,提问作者yvvt0379
相关产品推荐
相关产品推荐

