python3 线程的停止

转载: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,
 

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值