zoukankan      html  css  js  c++  java
  • python Synchronization between processes

    进程间同步,可以使用lock进行控制。

    官方文档的例子如下:

    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
    

    or

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

    运行结果:

    hello world first
    中间等待5秒钟
    hello world sec
    main process run OK
    

      

      

      

      

  • 相关阅读:
    redis命令
    eclipse error pages 打红X的解决方法
    探究adroid活动
    Javascript基本算法演练 Seek and Destroy
    c语言结构体排序示例
    android studio 环境配置
    git学习
    栈用于2进制转换10进制
    html和js
    js
  • 原文地址:https://www.cnblogs.com/hester/p/4911072.html
Copyright © 2011-2022 走看看