线程锁(互斥锁)

线程锁(互斥锁)(Lock)

  • 在开启多个线程的时候使用if、while、+-、\的时候会导致数据不安全(各个线程访问数据资源时会出现竞争状态,造成数据混乱)所以必须加锁

  • 代码:

    from threading import Thread,Lock
    
    a=0
    def son1(lock):
        with lock:
            for i in range(100):
                global a
                a+=1
    def son2(lock):
        with lock:
            global a
            for i in range(100):
                    a-=1
    
    lock=Lock()
    
    ret=Thread(target=son1,args=(lock,)).start()
    ret1=Thread(target=son2,args=(lock,)).start()
    
    print(a)
    
  • 单例模式中加线程锁(保证在开启多个线程的时候依旧使用同一个内存地址)

    import time
    from threading import Thread, Lock
    
    class A(object):
        from threading import Lock
        __instnce=None
        lock=Lock()
        def __new__(cls, *args, **kwargs):
            with cls.lock:
                if not cls.__instnce:
                        time.sleep(0.000001)
                        cls.__instnce=super().__new__(cls)
                return cls.__instnce
    
    def func():
        a=A()
        print(a)
    
    lock=Lock()
    for i in range(10):
        Thread(target=func).start()
    
上一篇:selenium+python自动化测试--alert弹框


下一篇:elsarticle.cls之paragraph ended before \@citex was complete