进程间数据是独立的,可以借助于队列或管道实现通信,二者都是基于消息传递的
虽然进程间数据独立,但可以通过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