Python 在使用最大线程时是否使线程池阻塞?
我正在尝试创建一个线程池,在将另一个线程添加到线程池之前,该线程池将在达到最大线程数时阻塞Python 在使用最大线程时是否使线程池阻塞?,python,threadpool,Python,Threadpool,我正在尝试创建一个线程池,在将另一个线程添加到线程池之前,该线程池将在达到最大线程数时阻塞 import thread_pool import time def slow_greeting(msg): time.sleep(5) print("Hello there {}".format(msg)) def main(): tp = thread_pool.ThreadPool(3) while True: print("Top of the
import thread_pool
import time
def slow_greeting(msg):
time.sleep(5)
print("Hello there {}".format(msg))
def main():
tp = thread_pool.ThreadPool(3)
while True:
print("Top of the loop")
tp.add_task(slow_greeting, 'a')
tp.add_task(slow_greeting, 'b')
tp.add_task(slow_greeting, 'c')
# Should block here, waiting for a free thread
tp.add_task(slow_greeting, 'd')
tp.add_task(slow_greeting, 'e')
但是,当运行此操作时,“循环顶部”会一次又一次地打印,而slow\u greeting
会在打印时运行
在尝试添加任务时,如何创建线程池块,直到至少有一个可用线程可供该任务运行?我不明白您的问题是什么,也不明白您为什么要这样做。你的代码做的正是它应该做的。打印“循环顶部”,但这并不意味着将另一个任务添加到池中。实际发生的情况(afaik)是循环一次又一次地运行,没有添加任务,直到池有了新任务的“位置”。执行print语句是因为没有条件说池中有空间时只打印。我想添加一个类似
sleep\u的语句,直到\u有点(tp)
。我希望在重复请求相同的RESTful web服务时执行此操作(响应被发送到回调函数)。在前几个连接中至少有一个完成之前,我不希望建立另一个连接,以及相关的处理。我不知道thread_pool是否有此功能,但通常在threading和queue中有某种类型的信号,可用于检查类似的内容。此示例不涉及池,但您可以看到如何使用队列来实现所需功能