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

 

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

  进程:html

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

 

  线程:python

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 Queuepost

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

    from multiprocessing import Manager性能

    queue = Manager().Queue()url

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

    from multiprocessing import Pipespa

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

    from multiprocessing import manager线程

    manager = manager()code

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

在使用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
相关文章
相关标签/搜索