python-线程池封装

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2020-10-27 19:03
# @Author : Nuonuo
# @Site : 
# @File : Multithreading_ frame.py
# @Software: PyCharm




from concurrent.futures import ThreadPoolExecutor#线程池
import threading
import time
import random


thread_quantity=int(input('线程数量:'))
renwu=[]
renwu_suliang=1000#任务总数
wancheng_renwu_su=0#完成任务数
run_thread_quantity=0#运行线程
threadLock = threading.Lock()#锁
thread_name=['thread:'+str(i) for i in range(thread_quantity)][::-1]
pool = ThreadPoolExecutor(max_workers=thread_quantity)#定义线程池






def run(tim):
    global run_thread_quantity,wancheng_renwu_su
    linsi=random.randint(1,9)
    time.sleep(linsi)

#======================================================
    threadLock.acquire()
    thread_name.append(tim)
    wancheng_renwu_su += 1
    print(tim, '结束', linsi,'完成任务数:',wancheng_renwu_su)
    run_thread_quantity-=1
    threadLock.release()










if __name__ == '__main__':
    kstime=time.time()
    while True:
        time.sleep(0.1)#刷新频率
        threadLock.acquire()
        jubu=renwu_suliang-wancheng_renwu_su
        print('线程池-空闲线程:',len(thread_name),'运行中线程:',run_thread_quantity,'剩余任务数量:',jubu,'任务总数:',renwu_suliang)
        if run_thread_quantity<thread_quantity and wancheng_renwu_su<renwu_suliang and jubu>run_thread_quantity:
            run_thread_quantity+=1
            future = pool.submit(run,(thread_name.pop()))
        elif jubu==0:
            print('跳出')
            break
        threadLock.release()
    pool.shutdown()
    print(time.time()-kstime)


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值