如何在Python线程中正确使用join(timeout)?

1 投票
1 回答
2771 浏览
提问于 2025-04-18 08:54

我该如何在下面的例子中正确使用join(timeout)这个函数呢?我发现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?'

1 个回答

1

你有一个 for 循环,它试图在每个线程上等待最多2秒钟。

第一次调用 .join() 时,等待了整整2秒,然后超时了。第二次也是如此。第三个线程在5秒后完成(也就是在第三次 .join(2) 调用后1秒),而第四个线程在被连接时已经完成了。所以总共的时间是2 + 2 + 1 = 5秒。

撰写回答