Recursive locks, deadlocks, recursive locks resolve the deadlock, semaphores

Recursive lock

  • Mutex
from threading import Lock
lock_1 = Lock()
lock_1.acquire()
lock_1.acquire()
print(123)
# 打印结果:无法打印,并且程序阻塞住了
  • Recursive lock
from threading import RLock
lock_2 = RLock()
lock_2.acquire()
lock_2.acquire()
print(123)
# 打印结果:123

Deadlock

  • Deadlock is when using a mutex, while open two locks, it will lead to deadlock
  • Because at the same time the lock can only be opened by a thread, before you can go to another thread to execute lock after closing the lock
  • Is a thread has not released a lock, but another thread has got the other key to the lock, resulting in the first thread of execution can not get the next key to the lock, there is no way to perform End
  • He and another thread you'll have to wait in a state of a need to open a lock, if under
from threading import Thread,RLock,Lock
import time

lock1 = Lock()

def foo(name):
    lock1.acquire()
    print(f"{name}抱起猫")
    time.sleep(3) # 模拟线程被中断去执行其他的线程
    lock1.acquire()
    print(f"{name}抱起狗")
    lock1.release()
    lock1.release()

def foo1(name):
    lock1.acquire()  # 注意看锁的名字,和上面的不一样
    print(f"{name}抱起狗")
    lock1.acquire()
    print(f"{name}抱起猫")
    lock1.release()
    lock1.release()

t = Thread(target=foo,args=('Cheer',)).start()
t1 = Thread(target=foo1,args=('PI',)).start()

# 打印结果:出现阻塞状态,程序一直不会结束,就一直僵着,因为两个线程都没有释放对方需要的锁

Recursive lock to solve deadlock

from threading import Thread,RLock,Lock
import time

lock1 = RLock()

def foo(name):
    lock1.acquire()
    print(f"{name}抱起猫")
    time.sleep(3) # 模拟线程被中断去执行其他的线程
    lock1.acquire()
    print(f"{name}抱起狗")
    lock1.release()
    lock1.release()

def foo1(name):
    lock1.acquire()  # 注意看锁的名字,和上面的不一样
    print(f"{name}抱起狗")
    lock1.acquire()
    print(f"{name}抱起猫")
    lock1.release()
    lock1.release()

t = Thread(target=foo,args=('Cheer',)).start()
t1 = Thread(target=foo1,args=('PI',)).start()

signal

from threading import Thread,Semaphore
import time
# 信息量:也就是厕所开放多少个坑,一次性运行的线程数,之前的加锁了,一次只有一个线程通过,这次不一样了,这次好几个

# 实例化一个信息量
sem = Semaphore(4) # 括号里面的数值是开放多少个"坑位"

def foo(i):
    sem.acquire()  # 和锁的用法一样
    print(f"哈哈哈,{i}进来了")
    time.sleep(i+1)
    sem.release()
    print(f"哈哈哈,{i}干完了")

for i in range(10):
    t = Thread(target=foo,args=(i,)).start()

Guess you like

Origin www.cnblogs.com/xiongchao0823/p/11543737.html