进程锁

在多进程中有一个进程锁,多进程为什么还要有锁呢,进程不是独立存在的吗,要锁干什么用能

 

栗子:

from multiprocessing import Process,Lock

def func(l,i):
    l.acquire()
    print("hello world" ,i)
    l.release()


if __name__ == "__main__":
    lock = Lock()
    for i in range(10):
        p = Process(target=func,args=(lock,i))
        p.start()

输出结果:

D:\7_Python\Python37\python.exe D:/7_Python/S14/其他/aaaa.py
hello world 0
hello world 1
hello world 3
hello world 2
hello world 4
hello world 5
hello world 9
hello world 7
hello world 6
hello world 8

Process finished with exit code 0

从结果上看,这个锁貌似没有什么用,但是我们发现这些进程在共享屏幕,如果没有进程锁,进程在打印结果时,可能出现输出结果会乱的情况。

posted @ 2020-01-06 11:15  goldtree358  阅读(329)  评论(0)    收藏  举报