Python中的线程池:如何随机生成20个任务
发布时间:2023-12-11 12:54:50
在Python中,可以使用concurrent.futures模块来创建线程池并管理任务的执行。线程池可以帮助我们同时处理多个任务,提高程序的性能和效率。下面是如何随机生成20个任务并使用线程池的示例代码:
import concurrent.futures
import random
import time
def task(number):
# 执行任务的函数,这里模拟任务执行需要的时间
time.sleep(random.randint(1, 5))
return f"Task {number} completed"
# 创建线程池
with concurrent.futures.ThreadPoolExecutor() as executor:
# 提交任务到线程池
task_results = [executor.submit(task, number) for number in range(1, 21)]
# 获取任务的执行结果
for future in concurrent.futures.as_completed(task_results):
try:
result = future.result()
print(result)
except Exception as e:
print(f"An exception occurred: {e}")
上述代码中,首先定义了一个task函数,用于执行任务。在这个示例中,任务只是简单地打印一个完成的信息,并模拟了需要的时间。
然后,使用ThreadPoolExecutor创建了一个线程池。在with语句块中,我们可以提交任务到线程池。
通过executor.submit(task, number)语句,我们将task函数作为参数提交给线程池,并传入任务的编号number作为参数。
然后,我们使用concurrent.futures.as_completed方法来获取任务的执行结果。这个方法返回一个迭代器,按照任务完成的顺序返回Future对象。
在一个for循环中,我们可以通过future.result()获取任务的结果。如果任务抛出了异常,可以通过捕获Exception来处理。
运行上述代码,可以得到类似以下的输出:
Task 20 completed Task 14 completed Task 1 completed Task 19 completed Task 2 completed Task 10 completed Task 3 completed Task 16 completed Task 12 completed Task 8 completed Task 11 completed Task 7 completed Task 4 completed Task 13 completed Task 15 completed Task 5 completed Task 17 completed Task 18 completed Task 9 completed Task 6 completed
注意,线程池的大小默认为CPU核心数,可以通过指定参数max_workers来设置线程池的大小。
