One 、 Dependent third-party package
multiprocessing
Two 、 Ideas
1、 Create a process pool , And set the process pool capacity
2、 Loop to put processes into the process pool
3、 Close process pool , No longer receive new process requests
4、 Wait for the execution of all child processes in the process pool to complete
import multiprocessing,os
from time import sleep
def demo(i):
''' Subprocesses '''
print('{:-^30} Start execution , The process number is {}'.format(i,os.getpid()))
sleep(0.5)
print('{:*^30} completion of enforcement , The process number is {}'.format(i,os.getpid()))
def main():
# Create a process pool , Set the process pool capacity
po=multiprocessing.Pool(3)
# Loop in processes to the process pool
#multiprocessing.Pool().apply_async( The object function to call ,( Parameter tuples passed to the objective function ,))
for i in range(10):
po.apply_async(demo,(i,))
print('{:~<20}'.format(' Start the main process '))
# Close process pool , No new requests will be received after closing
po.close()
# Wait for the execution of all child processes in the process pool to complete , Must be on close after
po.join()
print('{:~>20}'.format(' End main process '))
if __name__ == '__main__':
main()
Print the results :
You can see that the process number is only 3 individual , But it has been implemented many times .