searchusermenu
  • 发布文章
  • 消息中心
点赞
收藏
评论
分享
原创

python学习笔记一:ThreadPoolExecutor多线程处理及task使用

2024-10-10 02:06:33
216
0

一、基本介绍

ThreadPoolExecutor:处于concurrent.futures模块,常用于IO密集型任务,使用多线程处理,提高性能

task:本文中用于指代各个线程中处理的任务,重点介绍如何检查当前任务的状态

二、举例及说明

使用ThreadPoolExecutor,可以轻松的对多线程任务继续提交、管理并判断其状态,举例如下:

from concurrent.futures import ThreadPoolExecutor, wait, as_completed
import time

def test_func(name):
    print(f"Task {name} is starting.")
    time.sleep(2)
    print(f"Task {name} is finished.")
    return f"Result of task {name}"

#创建线程池
with ThreadPoolExecutor(max_workers=5) as executor:

    #提交任务
    tasks = [executor.submit(test_func, i) for i in range(5)]

    #检查任务完成情况
    all_done = all(task.done() for task in tasks)

    #取消任务
    for task in tasks:
        cancel = task.cancel()
        if cancel:
            print(f"Task {task} is canceled.")
        else:
            print(f"Task {task} cancel failed.")

    #等待所有任务完成
    done, not_done = wait(tasks)
    for task in done:
        print(task.result())

    #获取结果
    for future in as_completed(tasks):
        print(future.result())

方法说明:

done()方法:检查任务是否已完成,返回布尔值。

result()方法:获取任务的返回值。如果任务未完成或抛出异常,则会引发相应的异常。

wait()方法:用于阻塞当前线程,直到所有给定的 Future 对象完成。该方法返回一个包含完成和未完成的 Future 对象的集合。

as_completed()方法:用于处理异步任务的结果,以任务完成的顺序获取,使用此方法可以立即处理已经完成的任务,而不必等待所有任务都完成。

cancel()方法:用于取消一个尚未开始执行的异步任务。

参数说明:

max_workers:定义线程池中最大的工作线程数量。它决定了同时执行的最大线程数,上述代码仅指定了此项,设置为最多5个线程并发执行

thread_name_prefix:定义新创建线程的名称前缀,使用此参数可方便调试和跟踪

initializer:在每个线程启动时调用的可选可调用对象(例如函数)。通常用于设置线程级的状态或资源。

initargs:传递的参数。

例如:
executor = ThreadPoolExecutor(max_workers=5, thread_name_prefix='worker', initializer=init_worker, initargs=(42,))
一般来说,max_workers和thread_name_prefix使用较多,initializer和initargs使用较少,默认值为None

综上,使用python提供的上述方法,可以便捷的管理多线程任务,使任务执行更加的可控可靠。

0条评论
0 / 1000
s****n
2文章数
0粉丝数
s****n
2 文章 | 0 粉丝
s****n
2文章数
0粉丝数
s****n
2 文章 | 0 粉丝
原创

python学习笔记一:ThreadPoolExecutor多线程处理及task使用

2024-10-10 02:06:33
216
0

一、基本介绍

ThreadPoolExecutor:处于concurrent.futures模块,常用于IO密集型任务,使用多线程处理,提高性能

task:本文中用于指代各个线程中处理的任务,重点介绍如何检查当前任务的状态

二、举例及说明

使用ThreadPoolExecutor,可以轻松的对多线程任务继续提交、管理并判断其状态,举例如下:

from concurrent.futures import ThreadPoolExecutor, wait, as_completed
import time

def test_func(name):
    print(f"Task {name} is starting.")
    time.sleep(2)
    print(f"Task {name} is finished.")
    return f"Result of task {name}"

#创建线程池
with ThreadPoolExecutor(max_workers=5) as executor:

    #提交任务
    tasks = [executor.submit(test_func, i) for i in range(5)]

    #检查任务完成情况
    all_done = all(task.done() for task in tasks)

    #取消任务
    for task in tasks:
        cancel = task.cancel()
        if cancel:
            print(f"Task {task} is canceled.")
        else:
            print(f"Task {task} cancel failed.")

    #等待所有任务完成
    done, not_done = wait(tasks)
    for task in done:
        print(task.result())

    #获取结果
    for future in as_completed(tasks):
        print(future.result())

方法说明:

done()方法:检查任务是否已完成,返回布尔值。

result()方法:获取任务的返回值。如果任务未完成或抛出异常,则会引发相应的异常。

wait()方法:用于阻塞当前线程,直到所有给定的 Future 对象完成。该方法返回一个包含完成和未完成的 Future 对象的集合。

as_completed()方法:用于处理异步任务的结果,以任务完成的顺序获取,使用此方法可以立即处理已经完成的任务,而不必等待所有任务都完成。

cancel()方法:用于取消一个尚未开始执行的异步任务。

参数说明:

max_workers:定义线程池中最大的工作线程数量。它决定了同时执行的最大线程数,上述代码仅指定了此项,设置为最多5个线程并发执行

thread_name_prefix:定义新创建线程的名称前缀,使用此参数可方便调试和跟踪

initializer:在每个线程启动时调用的可选可调用对象(例如函数)。通常用于设置线程级的状态或资源。

initargs:传递的参数。

例如:
executor = ThreadPoolExecutor(max_workers=5, thread_name_prefix='worker', initializer=init_worker, initargs=(42,))
一般来说,max_workers和thread_name_prefix使用较多,initializer和initargs使用较少,默认值为None

综上,使用python提供的上述方法,可以便捷的管理多线程任务,使任务执行更加的可控可靠。

文章来自个人专栏
文章 | 订阅
0条评论
0 / 1000
请输入你的评论
0
0