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

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

 

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

 

相关文章:

  • 2021-09-17
  • 2021-10-18
猜你喜欢
  • 2021-05-13
  • 2021-06-04
  • 2021-10-15
  • 2021-05-29
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案