多进程之间不共享数据,但共享同一套文件系统,像访问同一个文件、同一终端打印,如果不进行同步操作,就会出现错乱的现象。
所有在 threading 存在的同步方式,multiprocessing 中都有类似的等价物,如:锁、信号量等。以锁的方式为例,我们来看一个终端打印例子。
不加锁
from multiprocessing import Process import os,time def target(): print('p%s is start' %os.getpid()) time.sleep(2) print('p%s is end' %os.getpid()) if __name__ == '__main__': for i in range(3): p=Process(target=target) p.start()
执行结果:
p7996 is start p10404 is start p10744 is start p7996 is end p10404 is end p10744 is end
加锁
from multiprocessing import Process, Lock import os,time def target(lock): lock.acquire() print('p%s is start' %os.getpid()) time.sleep(2) print('p%s is end' %os.getpid()) lock.release() if __name__ == '__main__': lock = Lock() for i in range(3): p=Process(target=target, args=(lock,)) p.start()
执行结果:
p11064 is start p11064 is end p1532 is start p1532 is end p11620 is start p11620 is end