• python--多进程


    多进程:

    import multiprocessing
    import time
    
    def run(name):
        time.sleep(2)
        print('hello', name)
    
    
    if __name__ == '__main__':
        for i in range(10):
            p = multiprocessing.Process(target=run, args=('bob %s' %i,))
            p.start()
    

    获取进程ID:

    from multiprocessing import Process
    import os
    
    def info(title):
        print(title)
        print('module name:',__name__)
        print('parent process:',os.getppid())
        print('process id:',os.getpid())
        print('
    
    ')
    
    def f(name):
        info('33[31;1mfunction f33[0m')
        print('hello',name)
    
    if __name__ == '__main__':
        info('33[32;1mmain process line33[0m')
        p = Process(target=f, args=('bob',))
        p.start()
        p.join()
    

    进程间互访:

    #进程队列互访
    from multiprocessing import Process, Queue
    def f(q):
        q.put([42, None, 'hello'])
    
    if __name__ == '__main__':
        q = Queue()
        p = Process(target=f, args=(q,))
        p.start()
        print(q.get())
        p.join()
    
    
    #使用管道实现
    from multiprocessing import Process, Queue, Pipe
    
    def f(conn):
        conn.send([42, None, 'hello'])
        conn.close()
    
    if __name__ == '__main__':
        parent_conn, child_conn = Pipe()
        p = Process(target=f, args=(child_conn,))
        p.start()
        print(parent_conn.recv())
        p.join()
    
    
    #线程队列互访
    import threading, queue
    def f(q):
        q.put([42, None, 'hello'])
    
    if __name__ == '__main__':
        q = queue.Queue()
        t = threading.Thread(target=f, args=(q,))
        t.start()
        print(q.get())
        t.join()
    

    进程间交互之Manager:

    from multiprocessing import Process, Queue, 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))
            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',d)
            print('l',l)
    
  • 相关阅读:
    python常用库
    python多线程
    python内存泄漏
    用python实现js语言里的特性
    nginx + uwsgi
    mysql语句
    urllib模块
    提取数据xpath,re,css
    selenium模块
    脱壳
  • 原文地址:https://www.cnblogs.com/guqing/p/6446102.html
Copyright © 2020-2023  润新知