python Synchronization between processes
进程间同步,可以使用lock进行控制。
官方文档的例子如下:
1 2 3 4 5 6 7 8 9 10 11 12 | from multiprocessing import Process, Lock def f(l, i): l.acquire() print 'hello world' , i l.release() if __name__ = = '__main__' : lock = Lock() for num in range ( 10 ): Process(target = f, args = (lock, num)).start() |
运行结果:
1 2 3 4 5 6 7 8 9 10 | hello world 0 hello world 1 hello world 2 hello world 3 hello world 4 hello world 5 hello world 6 hello world 7 hello world 8 hello world 9 |
or
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | from multiprocessing import Process, Lock from time import sleep def f(l, i): l.acquire() print 'hello world' , i l.release() def n(l,i): l.acquire() print 'hello world' , i sleep( 5 ) l.release() if __name__ = = '__main__' : lock = Lock() result = [] result.append(Process(target = n,args = (lock, 'first' ))) result.append(Process(target = f,args = (lock, 'sec' ))) for x in result: x.start() for x in result: x.join() print ( 'main process run OK' ) |
运行结果:
1 2 3 4 | hello world first 中间等待 5 秒钟 hello world sec main process run OK |
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步