如何在Python中编写线程等待

如何在Python中编写线程等待,python,multithreading,Python,Multithreading,我有一个线程,我想设置等待超时,或从主线程的信号 我想到了这个。它不起作用。为什么? import threading import time t1 = threading.Lock() cond = threading.Condition(t1) class myThread (threading.Thread): def __init__(self, threadID, name, counter): threading.Thread.__init__(self)

我有一个线程,我想设置等待超时,或从主线程的信号

我想到了这个。它不起作用。为什么?

import threading
import time

t1 = threading.Lock()
cond = threading.Condition(t1)

class myThread (threading.Thread):
    def __init__(self, threadID, name, counter):
        threading.Thread.__init__(self)
        self.threadID = threadID
        self.name = name
        self.counter = counter
    def run(self):
        print "Starting " + self.name
        t1.acquire()
        cond.wait(10)`enter code here`
        t1.release()
        print "%s,%s,%s" % (self.name, self.counter, 3)


# Create new threads
thread1 = myThread(1, "Thread-1", 1)

# Start new Threads
thread1.start()

time.sleep(2)
t1.acquire()
cond.notify_all()
time.sleep(2)
等待的时间小于
cond.wait(10)
等待的时间,同时仍获取
t1

您应该删除
time.sleep(2)
并将其替换为
thread1.join()
以等待
thread1
完成

加入([超时])

等待线程终止。这将阻止调用线程,直到 其join()方法被调用的线程将终止–正常情况下 或通过未处理的异常–或直到可选超时 发生。 ()


您没有释放主线程中的锁。 释放它,它就会工作(线程在
等待
存在后重新请求锁,但由于它已经被获取,线程被锁定)


这不正是重点吗?这
时间.sleep(2)
等待的时间小于
秒等待(10)
,因此线程可以抓住锁并阻止主线程继续执行自己?它不工作不足以进行MCVE。。。发生了什么?你期望发生什么?
# Start new Threads
thread1.start()
time.sleep(2)

t1.acquire()
cond.notifyAll()
t1.release()