Python模块multiprocessing & 实现多进程并发
专业植发师:
def s_m(q):
fruits = ['香蕉', '苹果', '梨', '车厘子', '橘子']
for i in fruits:
q.put(i)
print(f'[进程1]发送消息{i}')
time.sleep(1)
q.close()
def r_m(q):
# while 1:
# try:
# msg = q.get(block=True, timeout=5)
# print(f'[进程2]接受消息{msg},并销毁')
# except:
# q.close()
# break
# time.sleep(1)
while 1:
if not q.empty():
msg = q.get(block=False)
print(f'[进程2]接受消息{msg},并销毁')
else:
q.close()
break
time.sleep(1)
if __name__ == '__main__':
q = multiprocessing.Queue()
t1 = multiprocessing.Process(target=s_m, args=(q,))
t2 = multiprocessing.Process(target=r_m, args=(q,))
t1.start()
t2.start()
t1.join()
t2.join()
这两种会不会好点啊
|