• multiprocessing的进程通信Pipe和Queue


    pipe管道,2个进程通信,允许单项或者双向,multiprocessing.Pipe(duplex=False)为单项,默认双向

    示例:

    from multiprocessing import Process,Pipe
    import os
    
    def proc1(pipe):
        pipe.send('hello')
        print('proc1 rec:',pipe.recv())
    
    def proc2(pipe):
        print('proc2 rec:',pipe.recv())
        pipe.send('hello too')
    
    pipe = Pipe()
    
    p1 = Process(target=proc1,args=(pipe[0],))
    p2 = Process(target=proc2,args=(pipe[1],))
    
    p1.start()
    p2.start()
    p1.join()
    p2.join()

    Queue允许多个进程通信

    示例:

    import os,time
    import multiprocessing
    
    def inputQ(queue):
        info = str(os.getpid()) + '(put):' + str(time.time())
        queue.put(info)
    
    def outputQ(queue,lock):
        info = queue.get()
        lock.acquire()
        print(str(os.getpid()) + '(get):' + info)
        lock.release()
    
    rec1 = []
    rec2 = []
    lock = multiprocessing.Lock()
    queue = multiprocessing.Queue(3)
    
    for i in range(10):
        process = multiprocessing.Process(target=inputQ,args=(queue,))
        process.start()
        rec1.append(process)
    
    for i in range(10):
        process = multiprocessing.Process(target=outputQ,args=(queue,lock))
        process.start()
        rec2.append(process)
    
    for p in rec1:
        p.join()
    
    queue.close()
    
    for p in rec2:
        p.join()
  • 相关阅读:
    7.31 "简单"(大嘘)DP
    P2014 选课
    7.30 "简单"(大嘘)DP
    Codeforce 1131C Birthday (构造数组)
    洛谷 P1074【靶形数独】(DFS)
    NOIP2004【虫食算】(DFS)
    洛谷 P1025【数的划分】(DFS dp)
    洛谷P1019【单词接龙】(DFS)
    洛谷P1162【机器人搬重物】(BFS)
    洛谷P1141【01迷宫】
  • 原文地址:https://www.cnblogs.com/myprovencesky/p/5897148.html
Copyright © 2020-2023  润新知