python多线程中子线程的kill如何做

借鉴知乎上大神的做法。

在python的API里面并没有杀死线程的方法,要么你就调用pthread或者WinAPI,要么就利用daemon的特性:父线程退出时子线程就自动退出。
看API是怎么说的

A boolean value indicating whether this thread is a daemon thread (True) or not (False). This must be set before start() is called, otherwise RuntimeError is raised. Its initial value is inherited from the creating thread; the main thread is not a daemon thread and therefore all threads created in the main thread default to daemon = False.

The entire Python program exits when no alive non-daemon threads are left.

所以我们可以新建一个线程作为父线程,然后实际工作是在它的一个子线程里面做,父线程循环检测一个变量来决定是否退出。Talk is cheap


import threadingclass 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))
        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.stoppedthread = TestThread()thread.start()import timeprint('Main thread Wainting')time.sleep(2)thread.stop()thread.join()

转载于:https://my.oschina.net/shniu/blog/382869

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值