Python-进程通信

参考文章:https://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e542c000/001431927781401bb47ccf187b24c3b955157bb12c5882d000

进程间肯定是需要相互通信的。而进程间的通信方式有三种:

  • 共享存储
  • 消息传递
  • 管道通信

Python的multiprocessing模块包装了底层的机制,提供了Queue、Pipes等多种方式来交换数据

以共享存储方式的对同一个队列进行输入输出以完成通信为例:

在父进程中创建两个子进程,一个往Queue写入数据,一个从Queue读出数据

# -*- coding:utf-8 -*-
from multiprocessing import Process, Queue
import os, time
# import random

# 写数据进程执行代码
def write(q):
    print ("Process %s to write:" % os.getpid())
    for value in [1, 2, 3, 4]:
        print ("put value %d to queue" % value)
        q.put(value)
#        time.sleep(random.random())
        time.sleep(1)
# 读数据进程执行代码
def read(q):
    print ("Process %s to read" % os.getpid())
    while True:
        value = q.get()
        print ("Get %d from queue" % value)

if __name__ == "__main__":
    # 父进程中创建Queue,并传给各个子进程
    q = Queue()
    pw = Process(target=write, args=(q, ))
    pr = Process(target=read, args=(q, ))
    # 启动子进程
    pw.start()
    pr.start()
    pw.join()
    # 此处不可调用pr.join(),因为read是是循环,只能强行终止
#    pr.join()
    pr.terminate()

运行结果:

Process 5125 to write:
put value 1 to queue
Process 5126 to read
Get 1 from queue
put value 2 to queue
Get 2 from queue
put value 3 to queue
Get 3 from queue
put value 4 to queue
Get 4 from queue

Process finished with exit code 0

猜你喜欢

转载自blog.csdn.net/weixin_39721347/article/details/86546883
今日推荐