一 . 管道
Pipe Conn1 ,conn2 = Pipe ( )
二 . 数据共享
M = Manager ( )
Dic = m.dict({'name' : sbalex})
多个管道会导致数据安全的问题,会使数据丢失,我们就进行加锁Lock
三 . 回调函数
callback = call_back_func
import time
from multiprocessing import Pool,Process
import os
def func(n):
# print('xxxxxxxxxx')
print('子进程的pid',os.getpid())
return n*n,'约吗'
def call_back_func(x):
# print(x) #(9, '约吗')
print('call_back',os.getpid())
print(x[0])
if __name__ == '__main__':
pool = Pool(4)
pool.apply_async(func,args=(3,),callback=call_back_func)
# print('主进程的pid',os.getpid())
# pool.close()
# pool.join()
# time.sleep(1)
四 . 进程池(今天的重点)
Pool 是进程池模块
Map : 异步提交任务,参数
import time
from multiprocessing import Process,Pool
def func(i):
num = 0
for j in range(5):
num += i
if __name__ == '__main__':
pool = Pool(4)
p_list = []
start_time = time.time()
for i in range(100):
p = Process(target=func,args = (i,))
p_list.append(p)
p.start()
[pp.join() for pp in p_list]
end_time = time.time()
print(end_time -start_time)
s_time = time.time()
pool.map(func,range(100)) # map自带join+close
e_time = time.time()
print(e_time - s_time)
进程池同步方法,Apply :同步提交任务,直接可以收到返回值
import time
from multiprocessing import Process,Pool
def func(i):
num = 0
for j in range(5):
num += i
time.sleep(1)
print(num)
return num
if __name__ == '__main__':
pool = Pool(4)
for i in range(10):
res = pool.apply(func,args=(i,)) # 同步串行
# 第一个位置func,第二个位置传参,无敌传参, 任何参数都可以传
print(res)
进程池异步方法,Apply_async() 异步提交任务:res.get() 阻塞效果,Close join
import time
from multiprocessing import Process,Pool
def func(i):
num = 0
for j in range(5):
num += i
time.sleep(1)
# print(">>>",num)
return num
if __name__ == '__main__':
pool = Pool(4)
red_list = []
for i in range(10):
res = pool.apply_async(func,args=(i,))
# print(res)
red_list.append(res)
# print(res.get())
pool.close() # 不是关闭进程池,只是锁定
pool.join() #等待进程池中所有任务执行完,但是无法确认是否所有的任务真的全部执行完了,前面要加close方法
for resss in red_list:
print(resss.get())