python线程池完成任务例子
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2020-10-20 20:52
# @Author : Nuonuo
# @Site :
# @File : 多线程框架.py
# @Software: PyCharm
from concurrent.futures import ThreadPoolExecutor
import threading
import requests
import nuo
import random
threadLock = threading.Lock()#许可区
T=True
def run(xiancheng_biaozhi):
global wancheng_shuliang,xiancheng_shuliang,T
print('线程',xiancheng_biaozhi,'开始加载')
while T:
threadLock.acquire()
#print('线程',xiancheng_biaozhi,'获得acquire锁')
jubuzhuchesu = renwu_zhongshuliang - wancheng_shuliang
if xiancheng_shuliang > jubuzhuchesu:
threadLock.release()
break#进行任务数量判断 若任务数量小于线程数量则跳出循环 结束当前线程
#print('线程', xiancheng_biaozhi, '释放acquire锁')
threadLock.release()
#投递任务code=========================================================
a=random.randint(1,10)
nuo.time库_sleep(a)
if a>5:
pd=True
else:
pd=False
if pd:
threadLock.acquire()
wancheng_shuliang+=1
print('线程[' + str(xiancheng_biaozhi) + ']:succes',wancheng_shuliang,renwu_zhongshuliang)
threadLock.release()
threadLock.acquire()
xiancheng_shuliang -= 1
if xiancheng_shuliang<1:
threadLock.release()
if T:
T=False
print('结束线程-关闭线程池-T')
return
print('线程['+str(xiancheng_biaozhi)+']:线程关闭')
threadLock.release()
def xiancheng_jianche():
while True:
pd = []
for i in xcc:
pd.append(str(i.done()))
nuo.time库_sleep(0.1)
if 'False' not in pd:#进行线程数量判断 若pd中没有false则所有线程完成任务
break
elif 'True' in pd:
print('没有结束的线程----', pd.count('False'))
print(pd)
renwu=[]#定义任务列表
cuowu=[]#存放下载错误
renwu_zhongshuliang=100#总任务数 使用前修改
wancheng_shuliang=0#完成任务数量
xiancheng_shuliang=int(input('>>>>线程数量:'))#线程数量
if __name__ == '__main__':
ks_time=nuo.time库_取启动时间()
pool = ThreadPoolExecutor(max_workers=xiancheng_shuliang) # 申请一个线程池
xcc = [] # 定义存放线程对象的列表
xiancheng_biaozhi=1
for i in range(xiancheng_shuliang):#循环开启线程
future = pool.submit(run,xiancheng_biaozhi)#线程对象放进列表中
#print('开启线程-',future,'线程数量+1',len(xcc))
xiancheng_biaozhi+=1
nuo.time库_sleep(0.5)
xcc.append(future)
#print('开启完毕进行检测线程状态')
#xiancheng_jianche()
pool.shutdown()#关闭线程池
print(nuo.time库_取启动时间()-ks_time)
# for i in xcc:
# print(i.result())#获取结果