锁的意思就是:一个一个的执行
from multiprocessing import Process,Lock
import os
import time
def work(mutex):
mutex.acquire()
print('task[%s] 上厕所' %os.getpid())
time.sleep(3)
print('task[%s] 上完厕所' %os.getpid())
mutex.release() if __name__ == '__main__':
mutex=Lock()
p1=Process(target=work,args=(mutex,))
p2=Process(target=work,args=(mutex,))
p3=Process(target=work,args=(mutex,))
p1.start()
p2.start()
p3.start() print('主')
互斥锁
from multiprocessing import Process,Lock
import json
import time
import random
import os
def search():
dic=json.load(open('a',))
print('剩余票数%s' %dic['count']) def get_ticket():
dic=json.load(open('a',))
if dic['count'] > 0:
dic['count']-=1
json.dump(dic,open('a','w'))
print('%s 购票成功' %os.getpid())
def task(mutex):
search()
time.sleep(random.randint(1, 3)) #模拟购票一系列繁琐的过程所花费的时间
mutex.acquire()
get_ticket()
mutex.release()
if __name__ == '__main__':
mutex=Lock()
for i in range(50):
p=Process(target=task,args=(mutex,))
p.start()
模拟抢票