互斥锁

互斥锁:是将代码中的关于修改共享数据的 那一小部分代码变成串行,牺牲了效率保证数据安全
举例:
import json
import time,random
from multiprocessing import Process,Lock

def search(name):
    with open('db.json','rt',encoding='utf-8') as f:
        dic=json.load(f)
    time.sleep(1)
    print('%s 查看到余票为 %s' %(name,dic['count']))

def get(name):
    with open('db.json','rt',encoding='utf-8') as f:
        dic=json.load(f)
    if dic['count'] > 0:
        dic['count'] -= 1
        time.sleep(random.randint(1,3))
        with open('db.json','wt',encoding='utf-8') as f:
            json.dump(dic,f)
            print('%s 购票成功' %name)
    else:
        print('%s 查看到没有票了' %name)

def task(name):
    search(name) #并发
    get(name) #串行

if __name__ == '__main__':
    for i in range(10):
        p=Process(target=task,args=('路人%s' %i,))
        p.start()
结果:
路人3 查看到余票为 1
路人2 查看到余票为 1
路人0 查看到余票为 1
路人1 查看到余票为 1
路人6 查看到余票为 1
路人4 查看到余票为 1
路人7 查看到余票为 1
路人5 查看到余票为 1
路人9 查看到余票为 1
路人8 查看到余票为 1
路人2 购票成功
路人0 购票成功
路人8 购票成功
路人3 购票成功
路人1 购票成功
路人4 购票成功
路人9 购票成功
路人6 购票成功
路人7 购票成功
路人5 购票成功

db.json中count:1
结果会发现只有一张票,但是所有人都抢到票了,数据不安全
抢票
import json
import time,random
from multiprocessing import Process,Lock

def search(name):
    with open('db.json','rt',encoding='utf-8') as f:
        dic=json.load(f)
    time.sleep(1)
    print('%s 查看到余票为 %s' %(name,dic['count']))

def get(name):
    with open('db.json','rt',encoding='utf-8') as f:
        dic=json.load(f)
    if dic['count'] > 0:
        dic['count'] -= 1
        time.sleep(random.randint(1,3))
        with open('db.json','wt',encoding='utf-8') as f:
            json.dump(dic,f)
            print('%s 购票成功' %name)
    else:
        print('%s 查看到没有票了' %name)

def task(name,mutex):
    search(name) #并发
    mutex.acquire() #获取锁
    get(name) #串行
    mutex.release() #释放锁
    #另一种写法
    # with mutex:
    #     get(name)

if __name__ == '__main__':
    mutex = Lock()
    for i in range(5):
        p=Process(target=task,args=('路人%s' %i,mutex))
        p.start()
        # p.join() # join只能将进程的任务整体变成串行,只能第一个人抢到

结果:
路人1 查看到余票为 1
路人0 查看到余票为 1
路人2 查看到余票为 1
路人4 查看到余票为 1
路人3 查看到余票为 1
路人1 购票成功
路人0 查看到没有票了
路人2 查看到没有票了
路人4 查看到没有票了
路人3 查看到没有票了
抢票升级版

 

转载于:https://www.cnblogs.com/zhouhao123/p/11235526.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值