`ThreadedProcessPoolExecutor` 由修改后的 `ProcessPoolExecutor` 形成,它生成使用 `ThreadPoolExecutor` 实例来运行给定任务的进程。
项目描述
ThreadedProcessPoolExecutor类是一个Executor子类,它使用进程池和每个进程上的内部线程池来异步执行调用。
ThreadedProcessPoolExecutor由修改后的ProcessPoolExecutor形成,该 ProcessPoolExecutor 处理(最多max_processes)使用ThreadPoolExecutor 实例(最多max_threads)运行给定任务。
如果max_processes为None或未给出,它将默认为机器上的处理器数。
如果max_threads为None或未给出,它将默认为机器上的处理器数乘以5。
例子
from concurrent.futures import as_completed
import math
from threadedprocess import ThreadedProcessPoolExecutor
import requests
RNGURL = "https://www.random.org/integers/?num=1&min=1&max=100000000&col=1&base=10&format=plain&rnd=new"
def get_prime():
n = int(requests.get(RNGURL).text)
if n % 2 == 0:
return (n, False)
sqrt_n = int(math.floor(math.sqrt(n)))
for i in range(3, sqrt_n + 1, 2):
if n % i == 0:
return (n, False)
return (n, True)
with ThreadedProcessPoolExecutor(max_processes=4, max_threads=16) as executor:
futures = []
for _ in range(128):
futures.append(executor.submit(get_prime))
for future in as_completed(futures):
print('%d is prime: %s' % future.result())