如何正确使用以下示例中的join(timeout)函数?超时似乎对主线程的执行没有影响。在文档中,主线程被阻塞,直到线程加入或超时。
import threading,time
class Server(threading.Thread):
def __init__(self, hostname):
super(Server, self).__init__()
self.__hostname = hostname
def run(self):
print self.__hostname+' left'
time.sleep(5)
print self.__hostname+' back'
sem.release()
#init
sem = threading.BoundedSemaphore(4)
threads = []
for x in xrange(1,5):
sem.acquire()
t = Server('thread '+str(x))
threads.append(t)
t.start()
for t in threads:
t.join(2)
print 'why is this line executed by main thread 5 seconds after, not 2?'
发布于 2014-06-07 03:56:01
您有一个for
循环,它尝试以2秒的超时时间加入4个线程中的每个线程。
第一个.join()
调用花费了整整2秒,然后超时。第二个做同样的事情。第三个线程在5秒后结束(在第三个.join(2)
调用后1秒),而第四个线程在加入时已经完成。2+2+1= 5。
https://stackoverflow.com/questions/24089643
复制相似问题