Peterson算法是一个humble(谦虚)算法。
谦虚:【当进程的flag为true时,turn为另一个进程。】
伪代码:
有两个进程:i和j ,每个进程有一个flag标志,为true或者false,turn表示轮到哪个进程 。
初始化设置flag[i]=false;flag[j]=false;turn=i;
进程i:
do{
flag[i]=true;
turn=j;//humble
while(flag[j]==true && turn==j); //若满足,则在此waiting,因为while中无内容
//critical secton
flag[i]=false;
//remainder section
}while(true)
进程j:
do(
flag[j]=true;
turn=i;//humble
while(flag[i]==true && turn==i);//若满足,则在此waiting,因为while中无内容
//critical section
flag[j]=false;
//remainder section
}while(true)
python简单实现:
import threading
class PetersonAlgorithm:
def __init__(self):
self.flag = [False, False]
self.turn = 0
def lock(self, thread_id):
other = 1 - thread_id
self.flag[thread_id] = True
self.turn = thread_id
while self.flag[other] and self.turn == thread_id:
pass # 等待直到其他线程释放锁
def unlock(self, thread_id):
self.flag[thread_id] = False
class SharedResource:
def __init__(self):
self.shared_variable = 0
self.lock = PetersonAlgorithm()
def update_shared_variable(self, thread_id):
self.lock.lock(thread_id)
self.shared_variable += 1 # 临界区操作
print(f'Thread {thread_id} updated the shared variable to {self.shared_variable}')
self.lock.unlock(thread_id)
def main():
shared_resource = SharedResource()
def thread_function(thread_id):
for _ in range(5):
shared_resource.update_shared_variable(thread_id)
thread1 = threading.Thread(target=thread_function, args=(0,))
thread2 = threading.Thread(target=thread_function, args=(1,))
thread1.start()
thread2.start()
thread1.join()
thread2.join()
if __name__ == "__main__":
main()