Python3 -threadpool多线程多个参数传入示例
发布日期:2021-05-07 19:16:32 浏览次数:52 分类:精选文章

本文共 939 字,大约阅读时间需要 3 分钟。

threadpool模块:一个替代multiprocessing的老旧实现

在Python世界中,threadpool模块曾经是处理多线程任务的重要工具。尽管如今建议使用multiprocessing替代它,但它的简洁性依然吸引了一部分开发者。

使用threadpool实现多线程只需几行代码:

from threadpool import ThreadPoolpool = ThreadPool(poolsize)requests = makeRequests(some_callable, list_of_args, callback)[pool.putRequest(req) for req in requests]pool.wait()

它通过传入参数组来实现多线程,并且保证了执行顺序,参数顺序与传入时一致。

参数传递示例:

def hello(m, n, o):    print("m = %s, n = %s, o = %s" % (m, n, o))    if __name__ == '__main__':    # 方法一    lst_vars_1 = ['1', '2', '3']    lst_vars_2 = ['4', '5', '6']    func_var = [(lst_vars_1, None), (lst_vars_2, None)]        # 方法二    dict_vars_1 = {'m':'1', 'n':'2', 'o':'3'}    dict_vars_2 = {'m':'4', 'n':'5', 'o':'6'}    func_var = [(None, dict_vars_1), (None, dict_vars_2)]        pool = threadpool.ThreadPool(2)    requests = threadpool.makeRequests(hello, func_var)    [pool.putRequest(req) for req in requests]    pool.wait()

通过以上代码,可以轻松实现多线程任务,参数传递过程简洁高效。

上一篇:【Python+selenium】浏览器后台运行 隐藏窗口执行
下一篇:php session_start()判断是否开启

发表评论

最新留言

初次前来,多多关照!
[***.217.46.12]2025年04月09日 14时26分02秒