我正在尝试创建一个线程池,在将另一个线程添加到线程池之前,当达到最大线程数时会阻塞。
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_greeting
当它运行时会运行。
如何在尝试添加任务时创建线程池块,直到至少有一个可用线程可供该任务运行?