【发布时间】:2019-11-21 09:57:50
【问题描述】:
几周前我出于学习目的开始使用 Python。 我想知道是否可以从特定线程解锁信号量获取。还是有其他工具?
import threading, time
sem = threading.Semaphore
def thread1 (threadname):
#Code to do
#Condition thread1
time.sleep(0.001)
sem.acquire()
#Code 1
sem.release
def thread2 (threadname):
while (thread1.is_alive() == True):
if #Condition thread1
sem.acquire()
#Code 2
sem.release
我在线程 1 中的条件正好在 time.sleep 之前(所以线程 2 有时间用 .acquire 阻塞线程 1)。如果我没有那个time.sleep,结果就会不一致。
我现在得到了很好的结果,但我希望我的线程 2 总是在线程 1 开始“Code1”之前开始它的“if”,所以我可以删除那个 time.sleep(0.001) 并获得一致的结果。
你有什么想法吗?
【问题讨论】:
标签: python multithreading semaphore