账号密码登录
微信安全登录
微信扫描二维码登录

登录后绑定QQ、微信即可实现信息互通

手机验证码登录
找回密码返回
邮箱找回 手机找回
注册账号返回
其他登录方式
分享
  • 收藏
    X
    python 可重入锁有什么用?
    38
    0

    可重入锁:支持在同一线程中多次请求同一资源

    import threading
    import time
    class MyThread(threading.Thread):
      def run(self):
        global num
        time.sleep(1)
        if mutex.acquire(1):
          num = num+1
          msg = self.name+' set num to '+str(num)
          print(msg)
          mutex.acquire()
          print('Do another thing.')
          mutex.release()
          mutex.release()
    num = 0
    mutex = threading.RLock()
    def test():
      for i in range(5):
        t = MyThread()
        t.start()
    if __name__ == '__main__':
      test()

    那我既然一个线程要用两次共享变量,我直接acquire后我就不release,干嘛要acquire两次不是多此一举?
    直接只有一次acquire和一次release:

    import threading
    import time
    class MyThread(threading.Thread):
      def run(self):
        global num
        time.sleep(1)
        if mutex.acquire(1):
          num = num+1
          msg = self.name+' set num to '+str(num)
          print(msg)
          print('Do another thing.')
          mutex.release()
    num = 0
    mutex = threading.RLock()
    def test():
      for i in range(5):
        t = MyThread()
        t.start()
    if __name__ == '__main__':
      test()

    还是我学艺不精,说可重入锁是用来防止死锁的,那么可重入锁应该用在什么情况下?

    0
    打赏
    收藏
    点击回答
        全部回答
    • 0
    • 舒涓 普通会员 1楼

      在Python中,可重入锁(Reentrant Lock)是一种特殊类型的锁,它允许一个线程同时持有多个锁,但只能执行一次特定的代码块。这种特性对于共享资源的并发控制非常重要。

      以下是一个简单的可重入锁的实现:

      ```python import threading

      class ReentrantLock: def init(self): self._lock = threading.Lock()

      def acquire(self):
          with self._lock:
              # 当锁已存在时,线程将被阻塞,直到解锁为止
              pass
      
      def release(self):
          with self._lock:
              # 线程可以立即解锁,以避免阻塞
              pass
      

      ```

      在这个实现中,acquire方法用于获取锁,release方法用于释放锁。acquire方法返回一个布尔值,表示当前线程是否获得了锁。如果获取到了锁,那么就进入了一个无限循环,直到release方法被调用。release方法则会立即返回一个布尔值,表示当前线程是否释放了锁。

      使用可重入锁的一个重要应用是实现多线程同步。例如,我们可以使用可重入锁来同步多个线程对共享资源的访问。每个线程都有一个唯一的锁,当一个线程试图访问一个共享资源时,它会首先尝试获取这个锁。如果获取到了锁,那么这个线程就可以继续执行它的代码。如果获取不到锁,那么这个线程将被阻塞,直到它获取到了锁。

      ```python import threading

      lock = ReentrantLock() counter = 0

      def increment(): global counter counter += 1

      threads = [] for i in range(10): t = threading.Thread(target=increment) threads.append(t) t.start()

      for t in threads: t.join() ```

      在这个例子中,我们使用了可重入锁来同步多个线程对counter变量的访问。每个线程都获取了它的锁,然后执行它的increment函数。当所有线程都完成了increment函数的执行后,我们调用join方法来等待所有线程结束。

    更多回答
    扫一扫访问手机版
    • 回到顶部
    • 回到顶部