进程池和线程池

池的功能是限制进程数和线程数

什么时候限制?

当并发的任务数量远远大于计算机所能承受的范围,即无法一次性开启过多的任务数量

就应该考虑去限制进程数或线程数,从而保证服务器不崩

提交任务的两种方式:

同步:提交了一个任务,必须等任务执行完了(拿到返回值),才能执行下一行代码

异步:提交了一个任务,不要等执行完了,可以直接执行下一行代码

from concurrent.futures import ProcessPoolExecutor,ThreadPoolExecutor
from threading import currentThread
from multiprocessing import current_process
import time
#ThreadPoolExecutor:线程池,提供异步调用
#ProcessPoolExecutor: 进程池,提供异步调用

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

if __name__ == '__main__':
    pool = ThreadPoolExecutor(4) # 池子里只有4个线程
    # pool = ProcessPoolExecutor(4) # 池子里只有4个线程
    fu_list = []
    for i in range(20):
        # pool.submit(task,i) # task任务要做20次,4个线程负责做这个事
        future = pool.submit(task,i) # task任务要做20次,4个进程负责做这个事
        # print(future.result()) # 如果没有结果一直等待拿到结果,导致了所有的任务都在串行
        fu_list.append(future)
    pool.shutdown() # 关闭了池的入口,会等待所有的任务执行完,结束阻塞.
    for fu in fu_list:
        print(fu.result())


#回调函数

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

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


def parse(future):
    # 处理拿到的结果
    print(future.result())



if __name__ == '__main__':
    pool = ThreadPoolExecutor(4) # 池子里只有4个线程
    # pool = ProcessPoolExecutor(4) # 池子里只有4个线程
    fu_list = []
    for i in range(20):
        # pool.submit(task,i) # task任务要做20次,4个线程负责做这个事
        future = pool.submit(task,i) # task任务要做20次,4个进程负责做这个事
        future.add_done_callback(parse)
        # 为当前任务绑定了一个函数,在当前任务执行结束的时候会触发这个函数,
        # 会把future对象作为参数传给函数
        # 这个称之为回调函数,处理完了回来就调用这个函数.


        # print(future.result()) # 如果没有结果一直等待拿到结果,导致了所有的任务都在串行

    # pool.shutdown() # 关闭了池的入口,会等待所有的任务执行完,结束阻塞.
    # for fu in fu_list:
    #     print(fu.result())

posted on 2019-09-19 18:33  黑糖A  阅读(128)  评论(0编辑  收藏  举报