import multiprocessing as mp
import time
import multiprocessing as mp
import time
from multiprocessing import Manager
def job1(i,return_dict):
v=0
for i in range(100):
time.sleep(0.1)
v+= i # 获取共享内存
#print(v,end="
")
return_dict[i] = v
print("job1完成")
def job2(i,return_dict):
v=1
for i in range(100):
time.sleep(0.1)
v+= i # 获取共享内存
# print(v,end="
")
return_dict[i] = v
print("job2完成")
if __name__=='__main__':
t1 = time.time()
manager = Manager()
return_dict1= manager.dict()
return_dict2 = manager.dict()
return_dict3 = manager.dict()
return_dict4 = manager.dict()
# p1 = mp.Process(target=job1, args=(0,return_dict1)) # 需要将lock传入
# p2 = mp.Process(target=job2, args=(0,return_dict2))
# p3 = mp.Process(target=job1, args=(0, return_dict3)) # 需要将lock传入
# p4= mp.Process(target=job2, args=(0, return_dict4))
# p1.start()
# p2.start()
# p3.start()
# p4.start()
# p1.join()
# print(return_dict1.values())
# p2.join()
# print(return_dict2.values())
# p3.join()
# print(return_dict3.values())
# p4.join()
# print(return_dict4.values())
# #print(q.get())
# t2=time.time()
# print("时间为:",t2-t1)
job1(1,return_dict1)
job2(2,return_dict2)
job1(1, return_dict3)
job2(2, return_dict4)
print(return_dict1.values()[0])
print(return_dict2.values()[0])
print(return_dict3.values()[0])
print(return_dict4.values()[0])
t2=time.time()
print("时间为:",t2-t1)
import multiprocessing
from multiprocessing import Manager
def worker(procnum, return_dict):
'''worker function'''
print(str(procnum) + ' represent!')
return_dict[procnum] = procnum
#多进程实现结果
import time
if __name__ == '__main__':
manager = Manager()
# return_list = manager.list() 也可以使用列表list
return_dict = manager.dict()
jobs = []
t1=time.time()
for i in range(5):
p = multiprocessing.Process(target=worker, args=(i,return_dict))
jobs.append(p)
p.start()
for proc in jobs:
proc.join()
print(return_dict.values())