• 技术文章 >Python技术 >Python基础教程

    python进程之间如何通信

    小妮浅浅小妮浅浅2021-05-07 09:49:06原创3006

    本文教程操作环境:windows7系统、Python 3.9.1,DELL G3电脑。

    1、思路

    Process之间肯定是需要通信的,操作系统提供了很多机制来实现进程间的通信。Python的multiprocessing模块包装了底层的机制,提供了Queue、Pipes等多种方式来交换数据。

    2、实例

    以Queue为例,在父进程中创建两个子进程,一个往Queue里写数据,一个从Queue里读数据。

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    14

    15

    16

    17

    18

    19

    20

    21

    22

    23

    24

    25

    26

    27

    28

    29

    30

    31

    from multiprocessing import Process, Queue

    import os, time, random

      

    # 写数据进程执行的代码:

    def write(q):

        print('Process to write: %s' % os.getpid())

        for value in ['A', 'B', 'C']:

            print('Put %s to queue...' % value)

            q.put(value)

            time.sleep(random.random())

      

    # 读数据进程执行的代码:

    def read(q):

        print('Process to read: %s' % os.getpid())

        while True:

            value = q.get(True)

            print('Get %s from queue.' % value)

      

    if __name__=='__main__':

        # 父进程创建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()

    以上就是python进程之间通信的方法,希望能对大家有所帮助。更多Python学习指路:python基础教程

    专题推荐:python进程
    上一篇:python中jsonrpc的实现 下一篇:python中insort的使用

    相关文章推荐

    • python多进程取代多线程的探究• python协程的作用• python中jsonrpc的实现

    全部评论我要评论

    © 2021 Python学习网 苏ICP备2021003149号-1

  • 取消发布评论
  • 

    Python学习网