zoukankan      html  css  js  c++  java
  • 互斥锁

    互斥锁:是将代码中的关于修改共享数据的 那一小部分代码变成串行,牺牲了效率保证数据安全
    举例:
    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 查看到没有票了
    抢票升级版
  • 相关阅读:
    linux卸载rpm包
    Centos6.3手动rpm安装gcc,c++
    阿里云服务器挂载分区
    linux下svn目录管理
    mac搭建cordova的android环境
    mac下搭建cordova开发环境
    程序员除了写代码还可以做点啥
    php之soap使用
    linux中找不到/etc/sysconfig/iptables
    const 位置不一样导致的变化
  • 原文地址:https://www.cnblogs.com/zhouhao123/p/11235526.html
Copyright © 2011-2022 走看看