Python程序中的线程操作-concurrent模块

Python程序中的线程操作-concurrent模块

一、Python标准模块——concurrent.futures

官方文档:https://docs.python.org/dev/library/concurrent.futures.html

二、介绍

concurrent.futures模块提供了高度封装的异步调用接口

ThreadPoolExecutor:线程池,提供异步调用

ProcessPoolExecutor:进程池,提供异步调用

两者都实现相同的接口,该接口由抽象Executor类定义。

三、基本方法

submit(fn, *args, **kwargs):异步提交任务

map(func, *iterables, timeout=None, chunksize=1):取代for循环submit的操作

shutdown(wait=True):相当于进程池的pool.close()+pool.join()操作

  • wait=True,等待池内所有任务执行完毕回收完资源后才继续
  • wait=False,立即返回,并不会等待池内的任务执行完毕
  • 但不管wait参数为何值,整个程序都会等到所有任务执行完毕
  • submit和map必须在shutdown之前

result(timeout=None):取得结果

add_done_callback(fn):回调函数

done():判断某一个线程是否完成

cancle():取消某个任务

四、ProcessPoolExecutor

from concurrent.futures import ThreadPoolExecutor,ProcessPoolExecutor
from threading import currentThread
from multiprocessing import current_process
import time,os

def task(i):
    # print(f'{currentThread().name} 在运行 任务{i}')
    print(f'{current_process().name} 在运行 任务{i}')
    time.sleep(0.2)
    return i**2

if __name__ == '__main__':
    pool = ProcessPoolExecutor(4)
    fu_list = []
    for i in range(20):
        future = pool.submit(task,i)
        # print(future.result())  # 拿不到值会阻塞在这里。
        fu_list.append(future)

    pool.shutdown(wait=True)  # 等待池内所有任务执行完毕
    for i in fu_list:
        print(i.result())# 拿不到值会阻塞在这里。

五、ThreadPoolExecutor

from concurrent.futures import ThreadPoolExecutor,ProcessPoolExecutor
from threading import currentThread
from multiprocessing import current_process
import time,os

def task(i):
    # print(f'{currentThread().name} 在运行 任务{i}')
    print(f'{current_process().name} 在运行 任务{i}')
    time.sleep(0.2)
    return i**2

if __name__ == '__main__':
    pool = ThreadPoolExecutor(4)
    fu_list = []
    for i in range(20):
        future = pool.submit(task,i)
        # print(future.result())  # 拿不到值会阻塞在这里。
        fu_list.append(future)

    pool.shutdown(wait=True)  # 等待池内所有任务执行完毕
    for i in fu_list:
        print(i.result())# 拿不到值会阻塞在这里。

六、回调函数

from concurrent.futures import ThreadPoolExecutor,ProcessPoolExecutor
from threading import currentThread
from multiprocessing import current_process
import time,os

def task(i):
    # print(f'{currentThread().name} 在运行 任务{i}')
    print(f'{current_process().name} 在运行 任务{i}')
    time.sleep(0.2)
    return i**2
def parse(future):
    # print(future.result())
    # print(currentThread().name,'拿到了结果',future.result()) # 如果是线程池 执行完当前任务 负责执行回调函数的是执行任务的线程。
    print(current_process().name,'拿到了结果',future.result()) # 如果是进程池 执行完当前任务 负责执行回调函数的是执行任务的是主进程

if __name__ == '__main__':
    pool = ProcessPoolExecutor(4)
    # pool = ThreadPoolExecutor(4)
    fu_list = []
    for i in range(20):
        future = pool.submit(task,i)
        future.add_done_callback(parse) # 绑定回调函数
        # 当任务执行结束拿到返回值的时候自动触发回调函数。并且把future当做参数直接传给回调函数parse

原文地址:https://www.cnblogs.com/Lin2396/p/11568457.html

时间: 2024-08-08 15:15:48

Python程序中的线程操作-concurrent模块的相关文章

122 python程序中的线程操作-concurrent模块

一.concurrent模块的介绍 concurrent.futures模块提供了高度封装的异步调用接口 ThreadPoolExecutor:线程池,提供异步调用 ProcessPoolExecutor:进程池,提供异步调用 ProcessPoolExecutor 和 ThreadPoolExecutor:两者都实现相同的接口,该接口由抽象Executor类定义. 二.基本方法 submit(fn, *args, **kwargs):异步提交任务 map(func, *iterables, t

Python程序中的线程操作(线程池)-concurrent模块

目录 Python程序中的线程操作(线程池)-concurrent模块 一.Python标准模块--concurrent.futures 二.介绍 三.基本方法 四.ProcessPoolExecutor 五.ThreadPoolExecutor 六.map的用法 七.回调函数 Python程序中的线程操作(线程池)-concurrent模块 一.Python标准模块--concurrent.futures 官方文档:https://docs.python.org/dev/library/con

Python程序中的线程操作-锁

Python程序中的线程操作-锁 一.同步锁 1.1多个线程抢占资源的情况 from threading import Thread import os,time def work(): global n temp=n time.sleep(0.1) n=temp-1 if __name__ == '__main__': n=100 l=[] for i in range(100): p=Thread(target=work) l.append(p) p.start() for p in l:

119 python程序中的线程操作-守护线程

一.守护线程 无论是进程还是线程,都遵循:守护xx会等待主xx运行完毕后被销毁.需要强调的是:运行完毕并非终止运行. 对主进程来说,运行完毕指的是主进程代码运行完毕 对主线程来说,运行完毕指的是主线程所在的进程内所有非守护线程统统运行完毕,主线程才算运行完毕 1.1 详解 主进程在其代码结束后就已经算运行完毕了(守护进程在此时就被回收),然后主进程会一直等非守护的子进程都运行完毕后回收子进程的资源(否则会产生僵尸进程),才会结束. 主线程在其他非守护线程运行完毕后才算运行完毕(守护线程在此时就被

118 python程序中的线程操作-创建多线程

一.python线程的模块 1.1 thread和threading模块 thread模块提供了基本的线程和锁的支持 threading提供了更高级别.功能更强的线程管理的功能. 1.2 Queue模块 Queue模块允许用户创建一个可以用于多个线程之间共享数据的队列数据结构. 1.3注意模块的选择 避免使用thread模块 因为更高级别的threading模块更为先进,对线程的支持更为完善 而且使用thread模块里的属性有可能会与threading出现冲突: 其次低级别的thread模块的同

120 python程序中的线程操作-锁

一.同步锁 1.1 多个线程抢占资源的情况 from threading import Thread,Lock x = 0 def task(): global x for i in range(200000): x = x+1 # t1 的 x刚拿到0 保存状态 就被切了 # t2 的 x拿到0 进行+1 1 # t1 又获得运行了 x = 0 +1 1 # 这就产生了数据安全问题. if __name__ == '__main__': # 使用的是操作系统的原生线程. t1 = Thread

121 python程序中的线程操作-队列queue

一.线程队列 queue队列:使用方法同进程的Queue一样 如果必须在多个线程之间安全地交换信息时,队列在线程编程中尤其有用. 重要: q.put():往队列里面放值,当参数block=Ture的时候,timeout参数将会有作用,当队列已经满了的时候,在往里面放值时,block为True程序将会等待timeout的时间,过了时间程序会报错,block如果为Flase时,程序不会等待直接报错 q.get():从队列里面取值,当参数block=Ture的时候,timeout参数将会有作用,当队列

121 Python程序中的线程操作-线程定时器

目录 一.线程定时器 二.用法 一.线程定时器 线程定时器也是定时器,就是定时之后开启一条线程 二.用法 ''' 线程定时器,就是规定时间后开启一条线程 ''' def task(): print('线程执行了') time.sleep(2) print('线程结束了') t = Timer(4,task) # 间隔时间, 功能函数 t.start() 原文地址:https://www.cnblogs.com/XuChengNotes/p/11553061.html

Python程序中的进程操作-进程池(multiprocess.Pool)

Python程序中的进程操作-进程池(multiprocess.Pool) 一.进程池 为什么要有进程池?进程池的概念. 在程序实际处理问题过程中,忙时会有成千上万的任务需要被执行,闲时可能只有零星任务.那么在成千上万个任务需要被执行的时候,我们就需要去创建成千上万个进程么?首先,创建进程需要消耗时间,销毁进程也需要消耗时间.第二即便开启了成千上万的进程,操作系统也不能让他们同时执行,这样反而会影响程序的效率.因此我们不能无限制的根据任务开启或者结束进程.那么我们要怎么做呢? 在这里,要给大家介