进程同步-进程内部也需要锁

进程内部也需要锁。进程之间不能相互访问,为什么还需要锁???

因为他们是屏幕共享的,所以需要加个锁。防止打印出来是混乱的。

 

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()

 运行结果:

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

 

posted on 2017-08-14 16:16  momo8238  阅读(262)  评论(0编辑  收藏  举报