• 锁-lock


    锁-lock

    import time
    from multiprocessing import Lock,Process
    def func(i,lock):
        lock.acquire()   # 拿钥匙
        print('被锁起来的代码%s'%i)
        lock.release()  # 还钥匙
        time.sleep(1)
    
    def func1 (i ,lock):
        lock.acquire()
        print('被锁起来的代码%s'%i)
        lock.release()
        time.sleep(1)
    if __name__ == '__main__':
        lock = Lock()
        for i in range(10):
            p = Process(target=func1,args= (i,lock))
            p.start()
    
    import time
    from multiprocessing import Lock,Process
    def func(i,lock):
        lock.acquire()   # 拿钥匙
        print('被锁起来的代码%s'%i)
        lock.release()  # 还钥匙
        time.sleep(1)
    
    def func1 (i ,lock):
        with lock:      
    # 代替acquire和release 并且在此基础上做一些异常处理,保证即便一个进程的代码出错退出了,也会归还钥匙
            print('被锁起来的代码%s'%i)
        time.sleep(1)
    if __name__ == '__main__':
        lock = Lock()
        for i in range(10):
            p = Process(target=func1,args= (i,lock))
            p.start()
    

    抢票的例子:

    import json
    import time
    from multiprocessing import Process,Lock
    
    def search(i):
        with open('ticket',encoding='utf-8') as f:
            ticket = json.load(f)
        print('%s :当前的余票是%s张'%(i,ticket['count']))
    
    def buy_ticket(i):
        with open('ticket',encoding='utf-8') as f:
            ticket = json.load(f)
        if ticket['count']>0:
            ticket['count'] -= 1
            print('%s买到票了'%i)
        time.sleep(0.1)
        with open('ticket', mode='w',encoding='utf-8') as f:
            json.dump(ticket,f)
    
    def get_ticket(i,lock):
        search(i)
        with lock:   # 代替acquire和release 并且在此基础上做一些异常处理,保证即便一个进程的代码出错退出了,也会归还钥匙
            buy_ticket(i)
    
    
    if __name__ == '__main__':
        lock = Lock()     # 互斥锁
        for i in range(10):
            Process(target=get_ticket,args=(i,lock)).start()
    
  • 相关阅读:
    CSS基础(二十五)--Background背景之让background-image失效
    CSS基础(二十四)--Background背景之background-image平铺图片堆叠显示
    CSS基础(二十三)--Hover鼠标悬浮变色
    Nginx_安全1
    firewalld防火墙
    shell编程习题
    linux忘记密码
    sed和awk详解
    shell正则表达式
    ssh
  • 原文地址:https://www.cnblogs.com/wyh0717/p/13367240.html
Copyright © 2020-2023  润新知