美文网首页
04、多进程学习之——进程间通信

04、多进程学习之——进程间通信

作者: 牛在A和C之间 | 来源:发表于2020-07-28 18:58 被阅读0次

回想起在参考代码中队列有两类:torch.multiprocessing.Queue,queue.Queue。前者用在多进程里,作为多进程中target的参数;后者用在多线程中,作为多线程中target的参数。于是在代码中用前者替换后者,程序正常运行。
以一个案例来理解进程间通信

import random
import time
from multiprocessing import Process,Queue

# from queue import Queue
# 队列有两类:torch.multiprocessing.Queue,queue.Queue。
# 前者用在多进程里,作为多进程中target的参数;后者用在多线程中,作为多线程中target的参数。

class WriteProcess(Process):
    """ 写的进程 """
    def __init__(self, q, *args, **kwargs):
        self.q = q
        super().__init__(*args, **kwargs)

    def run(self):
        ls = [
            '第1行内容',
            '第2行内容',
            '第3行内容',
            '第4行内容',
            '第5行内容',
        ]
        for line in ls:
            print('写入内容:{0}'.format(line))
            self.q.put(line)
            # 每写入一次,休息1-5秒
            time.sleep(random.randint(1, 5))


class ReadProcess(Process):
    """ 读取内容的进程 """
    def __init__(self, q, *args, **kwargs):
        self.q = q
        super().__init__(*args, **kwargs)

    def run(self):
        while True:
            content = self.q.get()
            print('读取到的内容:{0}'.format(content))


if __name__ == '__main__':
    q = Queue()
    t_write = WriteProcess(q)
    t_write.start()

    t_read = ReadProcess(q)
    t_read.start()

    t_write.join()
    t_read.terminate()

相关文章

  • 04、多进程学习之——进程间通信

    回想起在参考代码中队列有两类:torch.multiprocessing.Queue,queue.Queue。前者...

  • linux进程间通信(1)

    一、进程通信概述 1、什么是进程间通信?什么是线程间通信? 进程间通信: 进程间通信就指的是用户空间中进程A与进程...

  • 第二十三章 进程间通信介绍(一)

    本章目标: 进程同步与进程互斥 进程间通信目的 进程间通信发展 进程间通信分类 进程间共享信息的三种方式 IPC对...

  • 进程间通信

    进程间通信 进程空间相对独立,资源无法相互获取,此时在不同进程间通信需要专门方法 进程间通信就是在不同的进程间进行...

  • 进程间的通信

    进程间的通信主要分为本机器进程间的通信和不同机器间进程的通信。本文主要描述本机进程间的通信。 一、传统Linux的...

  • 进程间通信,线程间通信

    进程间通信 进程间通信又称IPC(Inter-Process Communication),指多个进程之间相互通信...

  • Android IPC机制

    IPC 即Inter-Process-Communication,含义是进程间通信/跨进程通信。是指多个进程间通信...

  • 进程管理(五)进程间通信、死锁

    (一)进程间通信 除了同步和互斥外,进程间还有其他的通信手段。 进程间的通信 --> IPC (InterProc...

  • 6. 进程间通信

    参考链接:1. 进程间通信及使用场景2. 进程间通信机制IPC3. 看图理解进程间通信IPC==重点4. 进程间通...

  • IPC机制

    仅做个人学习记录 什么是IPC? inter-process-communication 进程间通信(跨进程通信)...

网友评论

      本文标题:04、多进程学习之——进程间通信

      本文链接:https://www.haomeiwen.com/subject/vekqrktx.html