本节内容:

  1. 多进程
  2. 协程
  3. 事件驱动与Select\Poll\Epoll异步IO

 

1.  多进程

  启动多个进程

  进程中启进程

  父进程与子进程

 

  进程间通信

  不同进程间内存是不共享的,要想实现两个进程间的数据交换,可以用以下方法:

a)   queues

  
#!/usr/bin/env python

# -*- coding:utf-8 -*-

from multiprocessing import Process, Queue

import queue

import threading

def f(qq):

    qq.put("hahaha123")

if __name__ == '__main__':

    #q = queue.Queue() #  线程queue不能直接传给子进程

    q = Queue()

    p = Process(target=f, args=(q,))

    #p = threading.Thread(target=f, args=(q,))

    p.start()

    print(q.get())

    p.join()
queues

  父进程克隆了一个Queue,将克隆的Queue交给了子进程,当一个Queue对数据进行修改时,会将修改后的Queue数据序列化到某一位置,另一个Queue会从这个位置反序列化获取数据,实现进程间的通信

b)   Pipes

  
#!/usr/bin/env python

# -*- coding:utf-8 -*- 

from multiprocessing import Process, Pipe

def f(conn):

    conn.send("qqqqqq")

    conn.send("qqqqqq2")

    print("from parent:", conn.recv())

    conn.close()

if __name__ == '__main__':

    parent_conn, chile_conn = Pipe()

    p = Process(target=f, args=(chile_conn,))

    p.start()

    print(parent_conn.recv())

    print(parent_conn.recv())

    parent_conn.send("hehehhe")

    p.join()
pipes

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案