python线程初步感受
python使用线程两种方法:
1,借助原始thread类,在初始化thread类时,嵌入自己的任务
2,定义自己的类来实现任务,这个类要继承thread类。
第一种方法:
from threading import Thread
import time
def func_A(str):
for i in range(10):
print("%s:%d"%(str,i))
time.sleep(1)
if __name__=="__main__":
#使用线程方式1
thread_func=Thread(target=func_A,args=("hello",))
thread_func.start();
print("你好1")
print("你好2")
print("你好3")
print("你好4")
print("你好5")
引入相关类:from threading import Thread
thread_func=Thread(target=func_A,args=("hello",))初始化一个线程,target嵌入自己的任务,args=(args1,args2,...)是个tuple类型,tuple类型的赋值有特殊之处:
tup1 = () # 空元组
tup2 = (20,) # 一个元素,需要在元素后添加逗号
以上栗子的结果如下:
hello:0你好1
你好2
你好3
你好4
你好5
hello:1
hello:2
hello:3
hello:4
hello:5
hello:6
hello:7
hello:8
hello:9
此处就是对线程的一个展示,打印“str:num”的顺序和“你好:num”的顺序是不一定的。
第二种方法:定义类,继承Thread这个父类,重写run方法
from threading import Thread
import time
def func_A(str):
for i in range(10):
print("fun_A: %s:%d"%(str,i))
time.sleep(1)
class A(Thread):
def __init__(self,**Kwargs):
Thread.__init__(self)
def run(self): #重写thread的run方法
for i in range(10):
print("A:",i)
time.sleep(1)
if __name__=="__main__":
#使用线程方式1
thread_func=Thread(target=func_A,args=("hello",))
thread_func.start();
print("你好1")
print("你好2")
print("你好3")
print("你好4")
print("你好5")
th=A();
th.run()
结果:
/Users/yxx/venv/bin/python /Users/yxx/PycharmProjects/python_learn/线程.py
fun_A: hello:0你好1
你好2
你好3
你好4
你好5
A: 0
A: 1
fun_A: hello:1
A: 2
fun_A: hello:2
A: 3
fun_A: hello:3
A:fun_A: hello:4
4
fun_A: hello:5
A: 5
fun_A: hello:6
A: 6
fun_A: hello:7
A: 7
fun_A: hello:8A: 8
A: 9
fun_A: hello:9
Process finished with exit code 0
结果完全不是顺序的。
python 多线程适合IO密集型事务,对CPU密集型事务可能不太适合。以下是模拟IO密集型任务的一个栗子,对比多线程与单线程性能:
'''
单线程与多线程性能对比
'''
import threading
import time
def request_data():
time.sleep(0.02) #模拟网络操作
# 单线程任务
def singe_thread():
for i in range(100):
request_data()
#多线程任务
def multi_thread():
thread_list=[]
for i in range(100):
t=threading.Thread(target=request_data)
t.start()
thread_list.append(t)
for i in thread_list:
i.join() #使得所有线程都执行完,再执行下面内容
if __name__=='__main__':
star_time=time.time()
singe_thread()
end_time=time.time()
print("单线程耗时:",(end_time-star_time))
star_time1 = time.time()
multi_thread()
end_time1 = time.time()
print("多线程耗时:", (end_time1 - star_time1))
运行结果:
单线程耗时: 2.325281858444214
多线程耗时: 0.034072160720825195
Process finished with exit code 0
性能提升还是很明显的