约定:
import threading
import time
Python线程Threading的简单教程
Python解释器使用了内部的GIL(全局解释器锁),在任意时刻只允许单个线程执行,无论有多少核,这限制了python只能在一个处理器上运行。当然使用多线程还是有好处的,不然也就没有存在的必要。当我们程序是I/O密集型,使用多线程会快很多。
线程也挺好理解的,程序必定有个主线程,而我们创建的线程都是在主线程下创建的。在主线程上,启动一个线程后就扔在一旁不管了,继续回到主线程执行它的代码,当然,线程间(包括主线程)的资源是共享的。
Thread对象
threading.Thread(group=None, target=None, name=None, args=(), kwargs=None, *, daemon=None)
group:为以后的扩展而保留。
target:调用对象,一般是函数。
name:线程名称。
args:传递给target函数的参数元祖。
kwargs:传递给target函数的关键字参数的字典。
daemon:是否为后台线程标志。
以函数的方式定义线程
#每隔5秒打印时间
def clock(wait_time,n):
for i in range(n):
print("The time is %s"%time.ctime())
time.sleep(wait_time)
t1=threading.Thread(target=clock,args=(5,3))
t1.setDaemon(True)
t1.start()
代码结果:
The time is Sat May 19 22:36:14 2018
The time is Sat May 19 22:36:19 2018
The time is Sat May 19 22:36:24 2018
以类的方式定义线程
class ClockThread(threading.Thread):
def __init__(self,wait_time,n):
threading.Thread.__init__(self) #必须要调用基类构造函数Thread.__init__()
self.deamon=True
self.t=wait_time
self.n=n
def run(self):
for i in range(self.n):
print("The time is %s"%time.ctime())
time.sleep(self.t)
t2=ClockThread(100,3)
t2.start()
代码结果:
The time is Sat May 19 23:53:46 2018
The time is Sat May 19 23:55:26 2018
The time is Sat May 19 23:57:06 2018
Thread对象的方法
- .start()启动线程:
一般是建立线程及设置好参数后运行的,且只能调用一次。
- .run()
是在线程启动后(调用.start())后执行的,且是程序自行调用的,还可以在子类中重新定义此方法。
- .is_alive()判断线程是否活动:
从start()方法开始直到run()终止这期间都是活动的。
t2.is_alive()
代码结果:
True
- .name()查看和更改线程名字:
t2.name="T"
t2.name
代码结果:
'T'
- .daeson(True)设置为后台线程:
注意要在start()前设置好。当不存在任何活动的非后台线程时,整个python程序将退出,也就是说无论是否有后台线程都将退出。
- .join([timeout]) 等待线程:
等待线程直到终止或超过timeout时间为止。
正确使用多线程的用法
当使用多线程时,要十分注意join()的用法,不然很可能将多线程变成单线程了。
#每隔5秒打印时间
def clock(wait_time,n):
for i in range(n):
print("The time is %s"%time.ctime())
time.sleep(wait_time)
T=[]
for i in range(3):
t=threading.Thread(target=clock,args=(5,2))
#t.setDaemon(True)
t.start()
T.append(t)
#等待所有进程结束
for t in T:
t.join()
print("all threads over")
代码结果:
The time is Sun May 20 00:02:15 2018
The time is Sun May 20 00:02:15 2018
The time is Sun May 20 00:02:15 2018
The time is Sun May 20 00:02:20 2018
The time is Sun May 20 00:02:20 2018
The time is Sun May 20 00:02:20 2018
all threads over
谢谢大家的浏览,
希望我的努力能帮助到您,
共勉!