join使得程序变成串行,一个一个执行,而lock可以让局部变成串行。
from multiprocessing import Process,Lock
import time
import json
def search(name):
time.sleep(1)
dic=json.load(open('db.txt','r',encoding='utf-8'))
print('<%s> 查看余票票数[%s]'%(name,dic['count']))
def get(name):
time.sleep(1)
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):
search(name)
get(name)
if __name__ == '__main__':
for i in range(10):
p= Process(target=task,args=('路人%s'%i,))
p.start()
p.join() #join使得程序变成串行,一个一个执行,而lock可以让局部变成串行。