本帖最后由 Sandwiches 于 2021-10-5 23:24 编辑
[Asm] 纯文本查看 复制代码 # -*- coding: utf-8 -*-
"""
Created on Tue Oct 5 23:15:22 2021
@author: Administrator
"""
from multiprocessing import Process, Queue
import os
import time
import random
def write(q):
print(f'Process to write: {os.getpid()}')
for value in ['A', 'B', 'C']:
print(f'Put {value} to queue...')
q.put(value)
time.sleep(random.random())
def read(q):
print(f'Process to read: {os.getpid()}')
while True:
value = q.get(True)
print(f'Get {value} from queue.')
def main():
# test queue
q = Queue()
pw = Process(target=write, args=(q,))
pr = Process(target=read, args=(q,))
# 启动子进程pw,写入:
pw.start()
# 启动子进程pr,读取:
pr.start()
# 等待pw结束:
pw.join()
# pr进程里是死循环,无法等待其结束,只能强行终止:
pr.terminate()
if __name__ == '__main__':
main()
|