python--多线程和线程池

python多线程

内建模块中的threading_thread的丰富版,提供了创建线程和启动线程的方法

# coding=utf-8
import threading
import time


start = time.time()
print("主线程:", threading.current_thread())


def handler():
    print('处理中')
    print("子线程:", threading.current_thread())
    time.sleep(5)
    print('处理完成')


t = threading.Thread(target=handler)
t1 = threading.Thread(target=handler)
t2 = threading.Thread(target=handler)
t3 = threading.Thread(target=handler)

t.start()
t1.start()
t2.start()
t3.start()

finish = time.time()

cost = finish - start

print("总耗时:", cost)


# 创建一个带参数的

执行结果:

主线程: <_MainThread(MainThread, started 21588)>
处理中
子线程: <Thread(Thread-1, started 19472)>
处理中
子线程: <Thread(Thread-2, started 11340)>
处理中
子线程: <Thread(Thread-3, started 10084)>
处理中
子线程: <Thread(Thread-4, started 14148)>
总耗时: 0.0020377635955810547
处理完成
处理完成
处理完成
处理完成

python线程池

python的线程池可以使用内建模块concurrent中的futures提供的ThreadPoolExecutor类来实例化一个线程池,其中max_worker参数是指该线程池中用于执行任务的worker最大个数,也就是该线程池中同时存在的线程个数上限,thread_name_prefix参数是可选参数,可以自己指定该线程池所创建的线程的名称前缀,可以用于与其他线程池创建的线程作区分。

# coding=utf-8
from concurrent.futures import ThreadPoolExecutor
import time
import threading


# 创建一个线程池
pool = ThreadPoolExecutor(max_workers=3, thread_name_prefix='pool')  


def handler(t):
    print("开始执行任务......", "当前时间:", time.time())
    print("当前线程:", threading.current_thread())
    time.sleep(t)
    print("任务执行完成!")


for i in range(10):
    pool.submit(handler, 3)


执行结果:

开始执行任务...... 当前时间: 1598371612.3126664
当前线程: <Thread(pool_0, started daemon 12340)>
开始执行任务...... 当前时间: 1598371612.3126664
当前线程: <Thread(pool_1, started daemon 1040)>
开始执行任务...... 当前时间: 1598371612.3136647
当前线程: <Thread(pool_2, started daemon 22440)>
任务执行完成!
任务执行完成!
开始执行任务...... 当前时间: 1598371615.316099
当前线程: <Thread(pool_2, started daemon 22440)>
开始执行任务...... 当前时间: 1598371615.316099
当前线程: <Thread(pool_0, started daemon 12340)>
任务执行完成!
开始执行任务...... 当前时间: 1598371615.316099
当前线程: <Thread(pool_1, started daemon 1040)>
任务执行完成!
任务执行完成!
开始执行任务...... 当前时间: 1598371618.3230267
当前线程: <Thread(pool_1, started daemon 1040)>
开始执行任务...... 当前时间: 1598371618.3230267
任务执行完成!
开始执行任务...... 当前时间: 1598371618.3240113
当前线程: <Thread(pool_0, started daemon 12340)>
当前线程: <Thread(pool_2, started daemon 22440)>
任务执行完成!
开始执行任务...... 当前时间: 1598371621.3355358
当前线程: <Thread(pool_0, started daemon 12340)>
任务执行完成!
任务执行完成!
任务执行完成!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值