One: Process pool
A process sequence is maintained internally by the process pool, and when used, a process is fetched to the process pool,
If there are no incoming processes available in the process pool sequence, the program waits until a process is available in the process pool.
There are two methods in a process pool:
Process pool apply is serial; Apply_async is parallel
The pool must first close in join, process pool after the process is completed and then closed, if the comment, then the program directly close
Two: code example
There are join codes and results
#-*-coding:utf-8-*-__author__='Shisanjun' fromMultiprocessingImportProcess,poolImport TimedefFoo (i): Time.sleep (2) returni+100defBar (ARG):Print("-->exec Done", Arg)if __name__=="__main__":#main If there is a manual run, execute main code below, if the import module does not executePool=pool (5) forIinchRange (10): Pool.apply_async (func=foo,args= (i,), callback=Bar)#Foo Executes the result as a parameter to bar #callback is the main process call, such as a database connection, if the child process generates a connection every time it consumes resources, once the main process is generated once Print("End") Pool.close () Pool.join ()#Process Pool After the process has finished executing and then closing, if the comment, then the program shuts down directly"""end-->exec done 100-->exec do 101-->exec done 102-->exec done 103-->exec do 104-->exec done 105- ->exec done 106-->exec do 107-->exec done 108-->exec done 109"""
Without the join code, the main process is finished executing the direct exit, so the child does not have the result output
#-*-coding:utf-8-*-__author__='Shisanjun' fromMultiprocessingImportProcess,poolImport TimedefFoo (i): Time.sleep (2) returni+100defBar (ARG):Print("-->exec Done", Arg)if __name__=="__main__":#main If there is a manual run, execute main code below, if the import module does not executePool=pool (5) forIinchRange (10): Pool.apply_async (func=foo,args= (i,), callback=Bar)#Foo Executes the result as a parameter to bar #callback is the main process call, such as a database connection, if the child process generates a connection every time it consumes resources, once the main process is generated once Print("End") Pool.close ()#Pool.join () #进程池中进程执行完毕后再关闭, if the comment, then the program closes directly
Python Basic Learning log day10-process pool