思考下列代码的执行结果有可能有哪些情况?为什么?
from multiprocessing import Process import time def foo(): print(123) time.sleep(1) print("end123") def bar(): print(456) time.sleep(3) print("end456") if __name__ == '__main__': p1=Process(target=foo) p2=Process(target=bar) p1.daemon=True p1.start() p2.start() print("main-------")
可能出现的情况如下,原因:主进程创建子进程,然后将该进程设置成守护自己的进程,守护进程会在主进程代码执行结束后就终止。
# 一般显示的结果 main------- 456 end456 # 倘若机器性能非常高 123 main------- 456 end456 # 倘若机器性能不是非常高,但也很强大 main------- 123 456 end456
使用互斥锁实现模拟购票
db,txt # 余票数据
{“count”: 5}
buy_ticket.py # 实现代码
from multiprocessing import Process, Lock import time import json def show(name): dic = json.load(open('db.txt', 'r', encoding='utf-8')) print('%s 查看,剩余票数为:%s ' % (name, dic['count'])) def get(name): time.sleep(0.5) dic = json.load(open('db.txt', 'r', encoding='utf-8')) if dic['count'] != 0: dic['count'] -= 1 time.sleep(0.5) json.dump(dic, open('db.txt', 'w', encoding='utf-8')) print('%s 购票成功' % name) else: print('%s 购票失败' % name) def run(name, muext): show(name) muext.acquire() get(name) muext.release() if __name__ == '__main__': muext = Lock() for i in range(10): p = Process(target=run, args=('用户 %s' % i, muext,)) p.start()