1 from multiprocessing import Process 2 import time 3 def task(name): 4 print(‘%s 美女正在活着‘ % name) 5 time.sleep(3) 6 print(‘%s 美女正在活着‘ % name) 7 if __name__ == "__main__" 8 p = Process(target = task, args = (‘Nami‘,)) 9 p.daemon = True 10 p.start() 11 print(‘jack寿终正寝‘)
1 from multiprocessing import Process, Lock 2 import json 3 import time 4 import random 5 6 7 #查票 8 def search(i): 9 #文件操作读取票数 10 with open(‘data‘,‘r‘,encoding=‘utf8‘) as f: 11 dic = json.load(f) 12 #模拟网络延迟 13 time.sleep(random.randint(1,3)) 14 #判断当前是否有票 15 if dic.get(‘ticket_num‘) > 0: 16 #修改数据库 买票 17 dic[‘ticket_num‘] -= 1 18 #写入数据库 19 with open(‘data‘,‘w‘,encoding=‘utf8‘) as f: 20 json.dump(dic,f) 21 print(‘用户%s买票成功‘ % i) 22 else: 23 print(‘用户%s买票失败‘ % i) 24 25 #整合上面两个函数 26 def run(i, mutex): 27 search(i) 28 #给买票环节加锁处理 29 #抢锁 30 mutex.acquire() 31 32 buy(i) 33 #释放锁 34 mutex.release() 35 if __name__ == ‘__main__‘: 36 #在主进程生成一把锁 让所有的子进程 谁先抢到票谁先买 37 mutex = Lock() 38 for i in range(1,11): 39 p = Process(target=run, args=(i,mutex)) 40 p.start() 41