我的问题:
我已经开始学习Python中的线程,所以我决定尝试实现“睡眠理发师问题”,只知道它背后的逻辑,但是,我遇到了一个问题:如果使用更多的线程和/或time.sleep()
时间太少(我使用它进行调试),我最终会得到一个RuntimeError: release unlocked lock
,由于它试图在我的“customer_ready”锁(在我的代码中是cliente_pronto
)已经被释放的时候释放它,根据我的理解(我可能是错的),这种事情不应该发生
我在这里错过了什么
我的代码:
import threading
barbeiro_pronto = threading.Lock()
wr_acessivel = threading.Lock()
cliente_pronto = threading.Lock()
num_assentos_livres = 10
clientes = []
barbeiro_pronto.acquire()
cliente_pronto.acquire()
def barbeiro():
global num_assentos_livres
global barbeiro_pronto
global wr_acessivel
global cliente_pronto
while (True):
cliente_pronto.acquire()
wr_acessivel.acquire()
num_assentos_livres+=1
barbeiro_pronto.release()
wr_acessivel.release()
def cliente():
global num_assentos_livres
global barbeiro_pronto
global wr_acessivel
global cliente_pronto
while (True):
wr_acessivel.acquire()
if num_assentos_livres > 0:
num_assentos_livres-=1
cliente_pronto.release()
wr_acessivel.release()
barbeiro_pronto.acquire()
return
else:
wr_acessivel.release()
thread_barbeiro = threading.Thread(target=barbeiro)
thread_barbeiro.start()
for i in range(15):
thread_cliente = threading.Thread(target=cliente)
thread_cliente.start()
clientes.append(thread_cliente)
while (True):
pass
我所尝试的:
尝试在释放此类锁之前放置if cliente_pronto.locked():
,但是这会导致问题,运行cliente
函数的所有线程要么返回未运行其所有代码的线程,要么与barbeiro
函数一起进入死锁(无法指出这两种情况中的哪一种似乎仅在我的调试中)
目前没有回答
相关问题 更多 >
编程相关推荐