• python 强制结束线程的坑


    网上流传了两种能强制结束线程的错误姿势

    第一种:通过setDaemon来结束线程

    http://www.cnblogs.com/jefferybest/archive/2011/10/09/2204050.html

    import threading
    import time
    def mythread(timeout,func):
        tHandle = threading.Thread(target=func)
        tHandle.setDaemon(True) 
        tHandle.start()
        tHandle.join(timeout) 
        print 'timeout'
    
     
    def do():
        while 1:
            time.sleep(0.2)
            print 'thread runing'
                           
    caller=threading.Thread(target=mythread,args=(1,do))
    caller.start()
    time.sleep(10)

    运行结果,并不会结束。因为setDaemon按照我的理解只跟主线程相关

    thread runing
    thread runing
    thread runing
    thread runing
    timeout
    thread runing
    thread runing
    thread runing
    thread runing
    thread runing
    thread runing
    thread runing
    thread runing

    第二种通过threading.Thread._Thread__stop()结束线程

    import time
    import threading
    def f():
        while 1:
            time.sleep(0.1)
            print 1
    
    
    t = threading.Thread(target=f)
    t.start()
    time.sleep(0.5)
    print "Stopping the thread"
    threading.Thread._Thread__stop(t)
    print "Stopped the thread"
    while 1:
        time.sleep(0.1)
        print t.isAlive()

    运行结果如下:猜测是_Thread__stop只是设置了线程结束的标记,并没有真正结束线程

    1
    1
    1
    1
    Stopping the thread
    Stopped the thread
    1
    False
    1
    False
    1
    False
    1
    False
    1
    False
    1
    False
    1
    False
    1
    False
    1
    False
    1
    False
    1
    False
    1
    False
    1
  • 相关阅读:
    setTimeOut与循环闭包问题
    ES6----class用法
    JS------对象的继承方式
    JavaScript对象 -构建
    nodejs异步---Async
    mongdb位置索引
    mongodb 索引3
    mongod 索引2
    mongodb 索引1
    3 C++数据类型
  • 原文地址:https://www.cnblogs.com/howmp/p/4977668.html
Copyright © 2020-2023  润新知