python中如何kill掉线程

在项目中碰到个问题,关于python的线程结束,python的threading库中没有相关的kill函数去结束线程,找到一种办法,我们可以新建一个线程作为父线程,然后在父线程中在起一个子线程来干我们的工作,父线程通过循环检测一个变量来决定是否退出,从而通过父线程的退出来,将工作的子线程退出,直接上代码看看


#!/usr/bin/env python
# coding: utf-8


import threading

class TestThread(threading.Thread):


    def __init__(self, thread_num=0, timeout=1.0):
        super(TestThread, self).__init__()
        self.thread_num = thread_num


        self.stopped = False
        self.timeout = timeout


    def run(self):
        def target_func():
            # inp = raw_input("Thread %d: " % self.thread_num)
            # print('Thread %s input %s' % (self.thread_num, inp))
            while True:
                pass
        subthread = threading.Thread(target=target_func, args=())
        subthread.setDaemon(True)
        subthread.start()


        while not self.stopped:
            subthread.join(self.timeout)


        print('Thread stopped')


    def stop(self):
        self.stopped = True


    def isStopped(self):
        return self.stopped


thread = TestThread()
thread.start()


import time
print('Main thread Wainting')
time.sleep(2)


thread.stop()
thread.join()


运行后的结果为:



评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值