进程与线程的通信机制----Queue

 

进程运行时候变量是隔离的,线程间共享全局变量。

  进程:

from multiprocessing import Process
from threading import Thread
def get(lis):
    while len(lis) != 0: # 注意一定要加上判定条件,不然进程不会退出的。
        s = lis.pop()
        print('get %s', s)

if __name__ == '__main__':
    lis = list(range(1, 11))
    process1 = Process(target=get, args=(lis,))
    process2 = Process(target=get, args=(lis,))
    process1.start()
    process2.start()
    process1.join()

get %s 10
get %s 10
get %s 9
get %s 9
get %s 8
get %s 8
get %s 7
get %s 7
get %s 6
get %s 6
get %s 5
get %s 4
get %s 5
get %s 3
get %s 4
get %s 2
get %s 3
get %s 1
get %s 2
get %s 1

  线程:

from multiprocessing import Process
from threading import Thread
def get(lis):
    while len(lis) !=0: # 注意一定要加判定条件,不然线程不会会一直等待,不会退出的。
        s = lis.pop()
        print('get %s', s)

if __name__ == '__main__':
    lis = list(range(1, 11))
    thread1 = Thread(target=get, args=(lis,))
    thread2 = Thread(target=get, args=(lis,))
    thread1.start()
    thread2.start()
    thread1.join()
    thread2.join()
    print('finished')

get %s 10
get %s 9
get %s 8
get %s 7
get %s 6
get %s 5
get %s 4
get %s 3
get %s 2
get %s 1
finished

进程与线程的Queue

  • 线程用的消息队列

    from queue import Queue

  • 进程用的消息队列

    from multiprocessing import Queue

  • 进程池用的消息队列(不能用from multiprocessing import Queue)

    from multiprocessing import Manager

    queue = Manager().Queue()

  • 特殊的,只用于两个进程间的通信Pipe(性能高于Queue,如果只有两个进程推荐使用)

    from multiprocessing import Pipe

  • 其它进程间的共享内存操作,列表、字典或其它python对象。

    from multiprocessing import manager

    manager = manager()

    my_list = manager.list() / my_dict = manager.dict()/

在使用Queue的时候,如果使用的默认的get后者put方法,(即(block=True, timeout=None))不管是多线程,还是多进程,在从队列中取出url的时候一定要加上判定条件,while queue.qsize()!=0  或者 while not queue.empty(),不然进程或者线程会一直等待。

from multiprocessing import Process, Pipe

def producer(queue):
    queue.send('bobby')

def comsumer(queue):
    print(queue.recv())

if __name__ == '__main__':
    recv_pipe, send_pipe = Pipe() 注意创建时候必须同时创建两个对象一个用于发送一个用于取出。
    my_producer = Process(target=producer, args=(send_pipe,))
    my_comsumer = Process(target=comsumer, args=(recv_pipe,))
    my_producer.start()
    my_comsumer.start()
    my_producer.join()
    my_comsumer.join()

输出:
bobby
原文地址:https://www.cnblogs.com/yc3110/p/10462867.html