转载:https://blog.csdn.net/ejennahuang/article/details/85060882
1、threading类
设置子线程为守护线程,(setdaemon=True),当主线程结束时,守护线程会自动结束
import threading
def run(x):
while x:
print(x)
t = threading.Thread(target=run,args=(4,), daemon=True)
#t.setdaemon(True)
#t.daemon=True
t.start() # 开始线程
# t.join() # join() 表示主线程阻塞,一直等子线程执行结束
2、类中直接设置标志位
import threading
class run():
def __init__(self):
self._flag=False
def run(self,x):
while x:
print(x,self._flag)
if self._flag:
break
def terminate(self):
self._flag = True
if __name__ == '__main__':
fun = run()
t = threading.Thread(target=fun.run, args=(5,))
t.start()
p=5
while p:
print(threading.activeCount())
p=p-1
fun.terminate()
t.join()
2.5、https://www.jb51.net/article/99237.htm
threading.Event()产生一个event对象。Event默认内置了一个标志,初始值为False,
set():将标志置为True;
Clear():则用于清除标志位(使之为False);
wait(timeout):当Event对象的内部信号标志为False时。wait方法一直堵塞线程等待到其为真或者超时(若提供,浮点数,单位为秒)才返回,若Event对象内部标志为True则wait()方法马上返回;
isSet():用于查询标志位是否为True,