我想要一些类似于Executors.newFixedThreadPool(3)的东西,它是用Java的。
也就是说,我希望我的python程序一次最多分3个多线程,如果现在的多线程数是3,则等到多线程数小于3。
蟒蛇身上有类似的东西吗?非常感谢!
发布于 2013-11-18 05:33:28
我想你需要的是一个信号量对象
threadLimiter = threading.BoundedSemaphore(maximumNumberOfThreads)
class YourThread(threading.Thread):
def run(self):
threadLimiter.acquire()
try:
<your code here>
finally:
threadLimiter.release()当启动线程超过最大线程数时,超限线程将在threadLimiter.acquire()中等待,直到某些线程结束。
发布于 2013-11-18 06:28:00
如果您正在运行python 3.2+,您可以访问concurrent.futures,这是一个高级线程模块,它方便地将其接口称为Executor。它有ThreadPoolExecutor和ProcessPoolExecutor两种口味。
#adapted example from docs
with concurrent.futures.ThreadPoolExecutor(max_workers=3) as executor:
future_results = [executor.submit(my_func, *args) for _ in range(100000)]
for result in concurrent.futures.as_completed(future_results):
#do something with each result检索许多urllib.request调用结果的更充实的示例可以是在文档里找到的。应该注意的是,这就是您应该使用许多线程进行I/O绑定的任务。由于GIL的原因,受处理器绑定的任务不会从多线程中获益--因此,使用ProcessPoolExecutor (它利用了multiprocessing)。
https://stackoverflow.com/questions/20040665
复制相似问题