import time, json
from multiprocessing import Process, Lock # 互斥锁
def serch(name):
time.sleep(1)
dic = json.load(open('db.txt', 'r', encoding='utf-8'))
print('%s查看到剩余票数是%s'%(name, dic['count']))
def get(name):
dic = json.load(open('db.txt', 'r', encoding='utf-8'))
if dic['count'] > 0:
dic['count'] -= 1
time.sleep(3)
json.dump(dic, open('db.txt', 'w', encoding='utf-8'))
print('%s抢票成功!'%name)
def task(name, mutex):
serch(name)
mutex.acquire() #开启互斥锁
get(name)
mutex.release() #关闭互斥锁
if __name__ == '__main__':
mutex = Lock() #互斥锁实例化
for i in range(10):
p = Process(target=task, args=('路人%s'%i, mutex)) #运用到子进程中一定要从父进程传入‘mutex’否则子进程会重新实例化互斥锁
p.start()
#互斥锁的的意义是只能单个进程进行,所以有开启互斥锁也就又关闭互斥锁的机制