用python创建2个进程,在这两个进程之间如何通信呢?
from multiprocessing import Queue, Process
import time, random
list1 = ['java', 'python', 'javascript']
def write(queue):
for value in list1:
print(f'正在向队列中添加数据-->{value}')
queue.put_nowait(value)
time.sleep(random.random())
def read(queue):
while True:
if not queue.empty():
value = queue.get_nowait()
print(f'从队列渠道获取的数据为-->{value}')
time.sleep(random.random())
else:
break
def main():
queue = Queue()
write_data = Process(target=write, args=(queue,))
read_data = Process(target=read, args=(queue,))
write_data.start()
write_data.join()
read_data.start()
read_data.join()
print('ok')
if __name__ == '__main__':
main()
正在向队列中添加数据-->java
正在向队列中添加数据-->python
正在向队列中添加数据-->javascript
从队列渠道获取的数据为-->java
从队列渠道获取的数据为-->python
从队列渠道获取的数据为-->javascript
ok
可以使用队列在进程之间进行通信
浙公网安备 33010602011771号