zoukankan      html  css  js  c++  java
  • python3 进程间的数据共享Manager

    进程间数据是独立的,可以借助于队列或管道实现通信,二者都是基于消息传递的
    虽然进程间数据独立,但可以通过Manager实现数据共享,但是,为了确保数据的安全性,需要通过加锁Lock来确保数据的安全性,如抢票.
    import os
    from multiprocessing import Process, Manager
    
    
    def func(l, d):
        l.append(os.getpid())
        d[os.getpid()] = os.getpid()
    
    
    if __name__ == '__main__':
        m = Manager()
        l = m.list(["init",])
        d = m.dict({"name":"lily",})
        p_lst = []
        for i in range(6):
            p = Process(target=func, args=(l, d))
            p_lst.append(p)
            p.start()
    
        [pp.join() for pp in p_lst]
        print(l)
        print(d)
    
    # ['init', 8584, 2524, 8892, 9096, 10036, 9072]
    # {'name': 'lily', 9096: 9096, 10036: 10036, 8584: 8584, 2524: 2524, 8892: 8892, 9072: 9072}
    
    
    


    # coding:utf-8
    import time
    from multiprocessing import Process, Lock, Manager
    
    
    def work(d, lock):
        with lock:
            d['count'] -= 1
    
    if __name__ == '__main__':
        start_time = time.time()
        lock = Lock()
        with Manager() as m:
            dic = m.dict({"count": 100})
            print(dic)
            p_l = []
            for i in range(100):
                p = Process(target=work, args=(dic, lock))
                p_l.append(p)
                p.start()
            for p in p_l:
                p.join()
            print(dic)
        end_time = time.time()
        print("程序执行的时间:", end_time - start_time)
    
        s_time = time.time()
        dic2 = {"count": 100}
        p_lst = []
        for i in range(100):
            p = Process(target=work, args=(dic2, lock))
            p_lst.append(p)
            p.start()
        for p in p_lst:
            p.join()
        e_time = time.time()
        print(dic2)
        print("程序执行的时间:", e_time - s_time)
    
    
    # {'count': 100}
    # {'count': 0}
    # 程序执行的时间: 12.078125
    # {'count': 100}
    # 程序执行的时间: 11.375
    
    

     

    
    
  • 相关阅读:
    DC中为什么要用Uniquify?
    hdu 1596 find the safest road
    hdu2112 HDU Today
    hdu 2066 一个人的旅行
    poj 3026 Borg Maze
    poj 1979 Red and Black
    poj 1321 棋盘问题
    hdu 1010 Tempter of the Bone
    hdu 4861 Couple doubi
    codeforces584B Kolya and Tanya
  • 原文地址:https://www.cnblogs.com/lilyxiaoyy/p/10985417.html
Copyright © 2011-2022 走看看