• python Manager and Pipe 简单操作


    Manager:

    from multiprocessing import Process, Manager
    import os
    
    def f(d, l):
        d[1] = '1'
        d['2'] = 2
        d[0.25] = None
        l.append(os.getpid())
        print(l)
    
    
    if __name__ == '__main__':
        with Manager() as manager:
            d = manager.dict()#生成一个字典,可在多个进程间共享和传递
    
            l = manager.list(range(5))#生成一个列表,可在多个进程间共享和传递
            print(l)
            p_list = []
            for i in range(10):
                p = Process(target=f, args=(d, l))
                p.start()
                p_list.append(p)
            for res in p_list:
                res.join()
    
            print(d)
            print(l)
    manager使用

     pipe(管道):

    from multiprocessing import Process, Pipe
    
    
    def f(conn):
        conn.send([42, None, 'hello'])#发送给parent_conn消息
        print('from parent:',conn.recv())#接受parent的消息
        conn.close()
    
    
    if __name__ == '__main__':
        parent_conn, child_conn = Pipe()#管道生成会返回两个对象
        p = Process(target=f, args=(child_conn,))
        p.start()
        print(parent_conn.recv())  # prints "[42, None, 'hello']",接受child_conn发送的消息
        parent_conn.send('hello childs')
        p.join()
  • 相关阅读:
    [C++] Class (part 2)
    [C++] Class (part 1)
    [c++] Inline Function
    [C++] in-class initializer
    简易线程池Thread Pool
    js里function的apply vs. bind vs. call
    webix custom component-九宫格
    webix源码阅读
    比特币的原理+问题
    wpf中UserControl的几种绑定方式
  • 原文地址:https://www.cnblogs.com/anhao-world/p/13737718.html
Copyright © 2020-2023  润新知