gpt4 book ai didi

java - 是否有与 Java 的 FixedThreadPool 等效的 Python 库?

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:10:11 24 4
gpt4 key购买 nike

Python 中是否有一个简单的 ThreadPool 库,例如 pool.execute(function, args) 方法,当池已满时应该阻塞该方法(直到其中一个线程空闲)?

我已经尝试使用 multiprocessing 包中的 ThreadPool,但它的 pool.apply_async() 函数不会在池已满时阻塞。实际上,我根本不了解它的行为。

最佳答案

ActiveState Code Recipes page有一个基于 Python queue 的实现做阻塞。在您要执行的地方使用add_task

## {{{ http://code.activestate.com/recipes/577187/ (r9)
from Queue import Queue
from threading import Thread

class Worker(Thread):
"""Thread executing tasks from a given tasks queue"""
def __init__(self, tasks):
Thread.__init__(self)
self.tasks = tasks
self.daemon = True
self.start()

def run(self):
while True:
func, args, kargs = self.tasks.get()
try: func(*args, **kargs)
except Exception, e: print e
self.tasks.task_done()

class ThreadPool:
"""Pool of threads consuming tasks from a queue"""
def __init__(self, num_threads):
self.tasks = Queue(num_threads)
for _ in range(num_threads): Worker(self.tasks)

def add_task(self, func, *args, **kargs):
"""Add a task to the queue"""
self.tasks.put((func, args, kargs))

def wait_completion(self):
"""Wait for completion of all the tasks in the queue"""
self.tasks.join()

if __name__ == '__main__':
from random import randrange
delays = [randrange(1, 10) for i in range(100)]

from time import sleep
def wait_delay(d):
print 'sleeping for (%d)sec' % d
sleep(d)

# 1) Init a Thread pool with the desired number of threads
pool = ThreadPool(20)

for i, d in enumerate(delays):
# print the percentage of tasks placed in the queue
print '%.2f%c' % ((float(i)/float(len(delays)))*100.0,'%')

# 2) Add the task to the queue
pool.add_task(wait_delay, d)

# 3) Wait for completion
pool.wait_completion()
## end of http://code.activestate.com/recipes/577187/ }}}

关于java - 是否有与 Java 的 FixedThreadPool 等效的 Python 库?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14699586/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com