进程池基础
import multiprocessing
import time
def work ( workNum) :
print ( f"{workNum}working........" , multiprocessing. current_process ( ) )
time. sleep ( 1 )
if __name__ == '__main__' :
# 创建线程池,指定线程个数
pool = multiprocessing. Pool ( 5 )
for i in range ( 10 ) :
# 同步, 轮流执行
# pool . apply ( work, ( f"work{i}" , ) )
# 异步,主进程不再等待线程池完成后退出
pool. apply_async ( work, ( f"work{i}" , ) )
# 异步,不再接收新的任务
pool. close ( )
# 异步,让主线程等待线程池完成
pool. join ( )
进程池中的消息队列
import multiprocessing
import time
def write_queue ( queue) :
for i in range ( 10 ) :
if queue. full ( ) :
print ( "队列已满" )
break
else :
queue. put ( i)
print ( "写入成功,已经写入" , i)
time. sleep ( 0.5 )
def read_queue ( queue) :
while True:
if queue. empty ( ) :
print ( "队列空了" )
break
else :
value = queue. get ( )
print ( "已经读取:" , value)
time. sleep ( 0.5 )
if __name__ == '__main__' :
# 创建线程池,指定线程个数
pool = multiprocessing. Pool ( 2 )
# 创建进程池中队列
queue = multiprocessing. Manager ( ) . Queue ( 5 )
# 同步方式
# pool . apply ( write_queue, ( queue, ) )
# pool . apply ( read_queue, ( queue, ) )
# 异步方式
# apply _async 返回值 ApplyResult对象的wait ( ) 方法表示先让当前进程执行完毕,后续进程才能启动
applyResult = pool. apply_async ( write_queue, ( queue, ) )
applyResult. wait ( timeout= 3 )
pool. apply_async ( read_queue, ( queue, ) )
pool. close ( )
pool. join ( )