Peterson algorithm

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()

  • 6
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值