Memory space for each child process will run multiple processes are isolated from each other process data can not be shared
A mutex
But between processes are running on a single operating system, do not share data between processes, but share the same set of file systems, so access to the same file, or print the same terminal,
It can, and bring the competition to share the results of the competition is to bring confusion
# Of concurrent operation, high efficiency, but competing for the same printing terminals, print distortions brought from multiprocessing Import Process Import Time DEF Task (name): Print ( " % S 1 " % name) the time.sleep ( 1 ) Print ( " % 2 S " % name) the time.sleep ( . 1 ) Print ( " % S. 3 " % name) IF the __name__ == ' __main__ ' : for I inRange (. 3 ): P = Process (target = Task, args = ( " subprocess S% " % I,)) p.start () '' ' sub-process 21 sub-process 01 the child 11 sub-process 2 2 sub-process 12 sub-process 02 the child 23 sub-process 13 sub-process 03 '' '
How to control, that is, the lock processing . The mutex mutually exclusive, which means that, if more than one process compared to more than one person,
Works mutex is more than one person have to go to a competition for the same resources: the bathroom, after a man grabbed a lock on the bathroom, the others have to wait until after the completion of this task releases the lock, there may be other people there is a grab ......
So mutex principle, is to change the serial concurrency, reduces efficiency, but to ensure data security, good chaos
Plus there is no mutex lock is only complicated by the effect of adding a mutex will run concurrently becomes less efficient the serial
solve:
Import module Lock
Now the program starts all the processes will first try to steal the lock only to grab the lock in order to run
such as run over the process to other processes continue to unlock and then grab the lock
from multiprocessing import Process, Lock import time def task(name, mutex): # 加锁 mutex.acquire() print("%s 1" % name) time.sleep(1) print("%s 2" % name) time.sleep(1) print("%s 3" % name) # 把锁拆了 mutex.release() if __name__ == '__main__' : # Build an object instance mutex = Lock () for i in the Range (3 ): # lock passed to the child process so that all children with the same lock the p-Process = (target = Task, args = ( " child process% S " % i, mutex)) p.start () '' ' now the program starts all the processes will first try to steal the lock only to grab the lock in order to run such as run over the process to other processes continue to unlock and then grab a lock ' '' '' ' sub-process 01 sub-process 02 sub-process 03 the child 11 sub-process 12 sub-process 13 sub-process 21 sub-process 22 sub-process 23 ' ''
At the expense of efficiency, ensure good data chaos