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

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

  • 相关阅读:
    一个涉及到浮点寄存器的CM
    树和二叉树一篇就搞定!
    串的两种模式匹配方式(BF/KMP算法)
    队列的知识讲解与基本实现(数据结构)
    如何用C++实现栈
    判断List集合为空还是null的正确打开方式
    双链表的基本实现与讲解(C++描述)
    Redis从认识安装到实现增删改查
    如何使用C++实现单链表
    线性表——顺序表的实现与讲解(C++描述)
  • 原文地址:https://www.cnblogs.com/sq5288/p/9347891.html
Copyright © 2011-2022 走看看