process_进程池_2

时间:2023-03-09 07:56:57
process_进程池_2
import multiprocessing
import os, time, random def Lee():
print("\nRun task Lee-%s" %(os.getpid()) ) #os.getpid()获取当前的进程的ID
start = time.time()
time.sleep(random.random() * 10) #random.random()随机生成0-1之间的小数
end = time.time()
print('Task Lee, runs %0.2f seconds.' %(end - start)) def Marlon():
print("\nRun task Marlon-%s" %(os.getpid()))
start = time.time()
time.sleep(random.random() * 40)
end=time.time()
print('Task Marlon runs %0.2f seconds.' %(end - start)) def Allen():
print("\nRun task Allen-%s" %(os.getpid()))
start = time.time()
time.sleep(random.random() * 30)
end = time.time()
print( 'Task Allen runs %0.2f seconds.' %(end - start)) def Frank():
print("\nRun task Frank-%s" %(os.getpid()))
start = time.time()
time.sleep(random.random() * 20)
end = time.time()
print( 'Task Frank runs %0.2f seconds.' %(end - start))
if __name__=='__main__':
function_list= [Lee, Marlon, Allen, Frank]
print( "parent process %s" %(os.getpid())) pool=multiprocessing.Pool(2)
for func in function_list:
pool.apply_async(func) print('Waiting for all subprocesses done...')
pool.close()
pool.join()
print('All subprocesses done.')
'''
parent process 3240
Waiting for all subprocesses done... Run task Lee-13652 Run task Marlon-13528
Task Lee, runs 3.34 seconds. Run task Allen-13652
Task Allen runs 14.78 seconds. Run task Frank-13652
Task Frank runs 2.45 seconds.
Task Marlon runs 32.62 seconds.
All subprocesses done.
'''