zoukankan      html  css  js  c++  java
  • 进程共享同步锁

    from multiprocessing import Process,Lock
    import os,time
    class work(Process):
        def __init__(self,lock):
            super().__init__()
            self.lock=lock
    
        def run(self):
            self.lock.acquire()
            print("%s is running"%os.getpid())
            time.sleep(2)
            print("%s is done"%os.getpid())
            self.lock.release()
    
    if __name__=='__main__':
        lock=Lock()
        for i in range(3):
            p=work(lock)
            p.start()
    
    
    
    # def work(lock):
    #     lock.acquire()
    #     print('%s is running'%os.getpid())
    #     time.sleep(2)
    #     print('%s is done'%os.getpid())
    #     lock.release()
    # if __name__ == '__main__':
    #     lock=Lock()
    #     for i in range(3):
    #         p=Process(target=work,args=(lock,))
    #         p.start()
    加锁可以保证多个进程修改同一块数据时,同一时间只能有一个任务可以进行修改,即串行的修改,没错,速度是慢了,但牺牲了速度却保证了数据安全。
  • 相关阅读:
    菜根谭#298
    菜根谭#297
    菜根谭#296
    菜根谭#295
    菜根谭#294
    菜根谭#293
    菜根谭#292
    菜根谭#291
    菜根谭#290
    菜根谭#289
  • 原文地址:https://www.cnblogs.com/wuxi9864/p/9980331.html
Copyright © 2011-2022 走看看