zoukankan      html  css  js  c++  java
  • Python:Day28 同步锁

    同步锁:

    Python不是有一把锁了吗?为什么还要加锁?

    Python解释器的GIL的作用是同一时刻只有一个线程被CPU执行,而同步锁的作用同一时刻只有一个线程对锁定代码块操作

     如果不加锁,当多个线程对同一数据操作的时候就有可能出问题,代码如下:

    import threading
    import time
    
    
    def minus_num():
        global num
        temp = num
        time.sleep(0.001)
        num = temp - 1
    
    
    num = 100
    threads = []
    for i in range(100):
        t = threading.Thread(target=minus_num)
        threads.append(t)
    for t in threads:
        t.start()
    for k in threads:
        k.join()
    print(num)

    加上同步锁后代码:

    import threading
    import time
    
    
    def minus_num():
        global num
        r.acquire()
        temp = num
        time.sleep(0.001)
        num = temp - 1
        r.release()
    
    
    num = 100
    threads = []
    r = threading.Lock()    # 创建一把锁,这个锁在任意时刻都只能被一个线程获取。
    for i in range(100):
        t = threading.Thread(target=minus_num)
        threads.append(t)
    for t in threads:
        t.start()
    for k in threads:
        k.join()
    print(num)  # 0

    死锁、递规锁

    import threading
    import time
    
    
    class MyThread(threading.Thread):
        def doA(self):
            lockA.acquire()
            print("%s get the lockA" % self.name)
            time.sleep(1)
            lockB.acquire()
            print("%s get the lockB" % self.name)
            lockA.release()
            lockB.release()
    
        def doB(self):
            lockB.acquire()
            print("%s get the lockB" % self.name)
            time.sleep(1)
            lockA.acquire()
            print("%s get the lockA" % self.name)
            lockA.release()
            lockB.release()
    
        def run(self):
            self.doA()
            self.doB()
    
    
    lockA = threading.Lock()
    lockB = threading.Lock()
    
    threads = []
    for i in range(5):
        threads.append(MyThread())
    
    for i in threads:
        i.start()
    
    for i in threads:
        i.join()
    
    print("----------the end----------")

    之所以出现死锁的现象是因为一个线程需要两把或两把以上的锁,且出现了锁套锁,并且其中一个锁被其它线程占用且不能释放,这样就造成了死其锁。

  • 相关阅读:
    pythonchallenge10
    线程同步
    查缺补漏
    查看QQ是否在线
    project euler10
    Toon Shading, step 2
    一种简易的卡通渲染方法(上)
    GLSL学习笔记 9.1 Transformation
    Gloss Mapping
    一种简易的卡通渲染方法(下)
  • 原文地址:https://www.cnblogs.com/sq5288/p/9347891.html
Copyright © 2011-2022 走看看