zoukankan      html  css  js  c++  java
  • python-day33--互斥锁

    锁的意思就是:一个一个的执行
     1 from multiprocessing import Process,Lock
     2 import os
     3 import time
     4 def work(mutex):
     5     mutex.acquire()
     6     print('task[%s] 上厕所' %os.getpid())
     7     time.sleep(3)
     8     print('task[%s] 上完厕所' %os.getpid())
     9     mutex.release()
    10 
    11 if __name__ == '__main__':
    12     mutex=Lock()
    13     p1=Process(target=work,args=(mutex,))
    14     p2=Process(target=work,args=(mutex,))
    15     p3=Process(target=work,args=(mutex,))
    16     p1.start()
    17     p2.start()
    18     p3.start()
    19 
    20     print('')
    互斥锁
     1 from multiprocessing import Process,Lock
     2 import json
     3 import time
     4 import random
     5 import os
     6 def search():
     7     dic=json.load(open('a',))
     8     print('剩余票数%s' %dic['count'])
     9 
    10 def get_ticket():
    11     dic=json.load(open('a',))
    12     if dic['count'] > 0:
    13         dic['count']-=1
    14         json.dump(dic,open('a','w'))
    15         print('%s 购票成功' %os.getpid())
    16 def task(mutex):
    17     search()
    18     time.sleep(random.randint(1, 3)) #模拟购票一系列繁琐的过程所花费的时间
    19     mutex.acquire()
    20     get_ticket()
    21     mutex.release()
    22 if __name__ == '__main__':
    23     mutex=Lock()
    24     for i in range(50):
    25         p=Process(target=task,args=(mutex,))
    26         p.start()
    模拟抢票
  • 相关阅读:
    关押罪犯
    食物链
    归并排序(分治)
    并查集+路径压缩
    3的幂的和
    斐波那契数列的第N项
    0和5
    扔盘子
    线段相交
    回文字符串
  • 原文地址:https://www.cnblogs.com/liuwei0824/p/7428483.html
Copyright © 2011-2022 走看看