Python_线程池 简单示例
时间:2020-07-22 13:54:10
收藏:0
阅读:69
from concurrent.futures import ThreadPoolExecutor
import time
import random
def start():
‘‘‘
主方法
‘‘‘
# 待处理列表
# 将此列表作为参数传递给线程池的执行器,
# 线程池会根据为列表中的每项单独分配一个线程,
# 并执行预定义方法。
lsn = range(100)
# 线程池中的线程数
threadCount = 3
# 使用线程池对列表执行预定义方法
with ThreadPoolExecutor(threadCount) as e:
e.map(threadFunction, lsn)
# 接收预定义方法的返回值
lre = []
# 使用线程池对列表执行预定义方法,并将返回结果加入列表
with ThreadPoolExecutor(threadCount) as e:
for item in e.map(threadFunction, lsn):
if item:
lre.append(item)
print(lre)
def threadFunction(sn):
‘‘‘
线程执行方法
‘‘‘
# 随机休眠
time.sleep(random.randint(1, 10)/100)
print(getTimeStamp(), sn)
return sn
def getTimeStamp():
# 时间戳 毫秒
shm = str(int(time.time()*1000))[-3:]
return time.strftime("%Y%m%d_%H%M%S_", time.localtime()) + shm
if __name__ == "__main__":
start()
原文:https://www.cnblogs.com/congxinglong/p/13359664.html
评论(0)