Multiprocessing Multiprocessing module
Take a look at the following methods:
- The star() method starts the process,
join() 方法实现进程间的同步,
Wait for all processes to exit.- close() is used to prevent excess processes from flooding into the process pool Pool and causing process blocking.
parameter:
- target is the function name, the function to be called
- The arguments required by the args function,
以 tuple 的形式传入
usage:
multiprocessing.Process(group=None, target=None, name=None, args=(), kwargs={}, *, daemon=None)
Write an example of:
from multiprocessing import Pool import os,time def pr(str): print("The " + str + " is %s" %(os.getpid())) time.sleep(1) print("The " + str + " is close") if __name__ == "__main__": print ( ' ----------------------------------------- ' ) print ( " the current pid: " + str(os.getpid ())) #The default is the number of cores of your computer p = Pool(2 ) for i in range(5 ): p.apply_async(pr,args=('xdxd',)) p.close() p.join() print("----------close-----------------")
It can be seen from the results that two processes are started at the same time, and the number of processes started at the same time is related to the number set in the pool and the number of cores of your computer
result:
------------------------------- the current pid: 9562 The xdxd is 9563 The xdxd is 9564 The xdxd is close The xdxd is close The xdxd is 9563 The xdxd is 9564 The xdxd is close The xdxd is close The xdxd is 9563 The xdxd is close ----------close-----------------