threading模块介绍:
创建线程对象:
threading.Thread(target=func)
- 参数
target
指定线程执行的任务(函数),注意是函数名;
Thread
类提供了以下方法:
start()
: 启动线程活动join(time)
:设置主线程会等待time秒后再往下执行,time默认子线程结束,多个字线程之间设置的值会叠加
来看一下刚才的单线程变成多线程后如何执行:
import time
from threading import Thread
def warpper(func):
def count_time():
start_time = time.time()
func()
end_time=time.time()
print('函数运行时间是:{:.5f}'.format(end_time-start_time))
return count_time
def work1():
for i in range(6):
time.sleep(1)
print('----work1--------')
def work2():
for i in range(5):
time.sleep(1)
print('----work2--------')
@warpper
def main():
t1 = Thread(target=work1) #创建线程对象
t2 = Thread(target=work2)
t1.start() #启动线程对象
t2.start()
print('---主线程把mian函数执行完毕----')
main()
print('----主线程执行函数之后的代码------')
运行结果:
---主线程把mian函数执行完毕----
函数运行时间是:0.00097
----主线程执行函数之后的代码------
----work1--------
----work2--------
----work2--------
----work1--------
----work2--------
----work1--------
----work2--------
----work1--------
----work1--------
----work2--------
----work1--------
发现装饰器计算的时间并不对,而且可以看出主线程执行完毕后才开始执行别的线程;
此时我们需要准确及时则需要让主线程等待别的线性执行:
可以使用join()方法进行等待:
import time
from threading import Thread
def warpper(func):
def count_time():
start_time = time.time()
func()
end_time=time.time()
print('函数运行时间是:{:.5f}'.format(end_time-start_time))
return count_time
def work1():
for i in range(6):
time.sleep(1)
print('----work1--------')
def work2():
for i in range(5):
time.sleep(1)
print('----work2--------')
@warpper
def main():
t1 = Thread(target=work1) #创建线程对象
t2 = Thread(target=work2)
t1.start() #启动线程对象
t2.start()
#设置主线程等待,等待线程执行完毕才会执行主线程
t1.join()
t2.join()
print('---主线程把mian函数执行完毕----')
main()
print('----主线程执行函数之后的代码------')
执行结果:
----work1--------
----work2--------
----work1--------
----work2--------
----work1--------
----work2--------
----work1--------
----work2--------
----work1--------
----work2--------
----work1--------
---主线程把mian函数执行完毕----
函数运行时间是:6.00294
----主线程执行函数之后的代码------
此时发现计算的时间也比较准确;
import time
from threading import Thread
import requests
def warpper(func):
def count_time():
start_time = time.time()
func()
end_time=time.time()
print('函数运行时间是:{:.5f}'.format(end_time-start_time))
return count_time
#定义线程类
class MyThread(Thread):
def run(self):
for i in range(10):
requests.get(url='https://www.baidu.com')
print("第"+str(i)+"次发送请求")
@warpper
def main():
t_list=[]
for i in range(10):
t = MyThread()
t.start()
t_list.append(t)
for t in t_list:
t.join()
if __name__ == '__main__':
main()
发现10个任务开启10个线程,1s即可执行完毕;