使用 ThreadPoolExecutor 实现无限循环的最佳方法是什么?
What is the best way to implement an infinite loop with ThreadPoolExecutor?
我的代码使用 ThreadPoolExecutor 来处理多个任务。主要要求之一是它可以无限期地执行。这是我当前的实现:
def process_something():
with ThreadPoolExecutor(max_workers=MAX_WORKERS1) as executor1:
with ThreadPoolExecutor(max_workers=MAX_WORKERS2) as executor2:
while True:
func1_returns = executor1.map(func1, arg1)
func2_returns = executor2.map(func2, arg2)
# code for processing func returns
time.sleep(1)
有没有更好的实现方式?这是否可能是内存泄漏,因为执行程序驻留在无限循环中?
线程池已经有多个线程可以使用。您不需要创建多个池。
def process_something():
with ThreadPoolExecutor(max_workers=MAX_WORKERS1) as executor1:
while True:
func1_returns = executor1.submit(func1, arg1)
func2_returns = executor1.submit(func2, arg2)
# code for processing func returns
time.sleep(1)
线程池中不应有任何内存泄漏。当 with
语句完成时,线程将被垃圾回收。
我的代码使用 ThreadPoolExecutor 来处理多个任务。主要要求之一是它可以无限期地执行。这是我当前的实现:
def process_something():
with ThreadPoolExecutor(max_workers=MAX_WORKERS1) as executor1:
with ThreadPoolExecutor(max_workers=MAX_WORKERS2) as executor2:
while True:
func1_returns = executor1.map(func1, arg1)
func2_returns = executor2.map(func2, arg2)
# code for processing func returns
time.sleep(1)
有没有更好的实现方式?这是否可能是内存泄漏,因为执行程序驻留在无限循环中?
线程池已经有多个线程可以使用。您不需要创建多个池。
def process_something():
with ThreadPoolExecutor(max_workers=MAX_WORKERS1) as executor1:
while True:
func1_returns = executor1.submit(func1, arg1)
func2_returns = executor1.submit(func2, arg2)
# code for processing func returns
time.sleep(1)
线程池中不应有任何内存泄漏。当 with
语句完成时,线程将被垃圾回收。