并发编程之线程池进程池

线程池与进程池

池:表示容器。线程池就是存放线程的容器,进程池就是存放进程的容器

为什么要存放到线程池、进程池中

  1. 避免频繁的创建和销毁(进程、线程)来的资源开销
  2. 可以限制同时存在的线程数量,以保证服务器不会因为资源不足而崩溃
  3. 帮我们管理了线程的创建和销毁
  4. 管理了任务的分配

进程池:

# 进程池
from concurrent.futures import ProcessPoolExecutor
from multiprocessing import Process
import os
import time

def task():
    time.sleep(0.1)
    print(os.getpid())


if __name__ == '__main__':
    pool = ProcessPoolExecutor(3)
    # 提交任务到池子中
    pool.submit(task)
    # time.sleep(1)
    pool.submit(task)
147332
147320

线程池:

# 线程池
from concurrent.futures import ThreadPoolExecutor

from threading import  active_count,enumerate,currentThread
import os
import time

def task():
    print(currentThread().name)
# 创建线程池
pool = ThreadPoolExecutor(3)

# 提交任务到池子中
pool.submit(task)
pool.submit(task)

print(f"{enumerate()}")
print(f"{active_count()}")
ThreadPoolExecutor-0_0
ThreadPoolExecutor-0_0
[<_MainThread(MainThread, started 135020)>, <Thread(ThreadPoolExecutor-0_0, started daemon 134904)>, <Thread(ThreadPoolExecutor-0_1, started daemon 134872)>]
3

如果主进程不结束,池子里面的进程或线程,也是一直存活的

转载于:https://www.cnblogs.com/plf-Jack/p/11139895.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值