python3 进程间的数据共享

进程间数据是独立的,可以借助于队列或管道实现通信,二者都是基于消息传递的
虽然进程间数据独立,但可以通过Manager实现数据共享,事实上Manager的功能远不止于此
# 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
 

猜你喜欢

转载自www.cnblogs.com/lilyxiaoyy/p/10985417.html