32多线程与线程池构建
创建多线程
# coding=gbk
# -*- coding:uft-8 -*-
# @Time: 2022/12/20
# @Author: 十架bgm
# @FileName: 创建线程时传递参数
import time
import threading
def fun1(num):
for i in range(num):
print('1111')
time.sleep(0.1)
def fun2(num1,num2):
for i in range(num1):
print('2222')
time.sleep(0.1)
for i in range(num2):
print('3333')
time.sleep(0.1)
def fun3(num1,num2,num3,n):
print(f'-------num1:{num1},num2:{num2},num3:{num3},n:{n}')
t1 = threading.Thread(target=fun1,args=(3,)) # arg参数必须传递
t2 = threading.Thread(target=fun2,args=(3,4))
t3 = threading.Thread(target=fun3, args=(11,22,33),kwargs={"n": 44}) # 带元组与字典
# 或者 t3 = threading.Thread(target=fun3, args=(11,22),kwargs={"n": 44,"num3":33})
t1.start()
t2.start()
t3.start()
运行一个程序,最少有一个线程,即主线程,经过threading.Thread()实例了一个对象,调用start方法,即增加了一个子线程,子线程跑完立即结束,主线程要等待所有的子线程全结束,主线程才会真正的结束,原因:主线程有个特殊功能用来对子线程产生的垃圾,进行回收处理。当主线程结束后,才意味这整个程序结束。
线程池
from concurrent.futures import ThreadPoolExecutor
def func(name): # 下载图片的任务
for i in range(100):
print(name, i)
if __name__ == '__main__':
# 创建线程池
with ThreadPoolExecutor(10) as t:
# 10个任务
# 把任务提交给线程池
t.submit(func, "周杰伦")
t.submit(func, "今")
t.submit(func, "天")
t.submit(func, "天")
t.submit(func, "气")
t.submit(func, "情")
t.submit(func, "周")
t.submit(func, "周杰")
t.submit(func, "杰")
t.submit(func, "伦")
// # for i in range(10000):
# t.submit(func,f'任务{i}')
本文来自博客园,作者:__username,转载请注明原文链接:https://www.cnblogs.com/code3/p/16994275.html