Python threading.Thread() 线程的终止

方法一:利用setDaemon(True)方法

将子线程设置为“守护线程”,即主线程停止,子线程也会停止。但是会等待非守护线程执行完毕。主线程退出

将一个用户线程设置为守护线程的方式是在线程对象创建之前,用线程对象的setDaemon方法。

import threading
import time
def run():
    while True:
        print("task")
        time.sleep(2)
        print("task has done!")
start_time=time.time()

t=threading.Thread(target=run)
#t.setDaemon(True)
t.start()

time.sleep(1)
print(threading.current_thread(),threading.active_count())
print(time.time()-start_time)
#由于未设置守护进程,即使主线程已完成工作,但非守护线程还未执行完毕
task
<_MainThread(MainThread, started 12864)> 2
1.0013351440429688
task has done!
task
task has done!
task
task has done!
task
...
import threading
import time
def run():
    while True:
        print("task")
        time.sleep(2)
        print("task has done!")
start_time=time.time()

t=threading.Thread(target=run)
t.setDaemon(True)
t.start()

time.sleep(1)
print(threading.current_thread(),threading.active_count())
print(time.time()-start_time)
task
<_MainThread(MainThread, started 16556)> 2
1.0004169940948486

方法二:通过重构Thread类

重写run()方法,并且添加第三方函数stop()来终止循环

import threading
import time

class Mythread(threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self)
        self.running = True


    def stop(self):
        self.running = False

    def run(self):
        while self.running:
            print(threading.get_ident(),'(o-o)!')
            time.sleep(1)

t1 = Mythread()
t2 = Mythread()
t1.start()
t2.start()
time.sleep(5)
t1.stop()
t2.stop()
19716 (o-o)!
16076 (o-o)!
19716 (o-o)!
16076 (o-o)!
1971616076  (o-o)!(o-o)!

1971616076 (o-o)! (o-o)!

19716 (o-o)!
16076 (o-o)!

方法三:通过threading.Event()方法

可以在不同线程中实现通信

threading模块和threading.Thread()子类

方法四:ctypes and inspect

具体不懂

import threading
import ctypes
import inspect

def _async_raise(tid, exctype):
    """raises the exception, performs cleanup if needed"""
    tid = ctypes.c_long(tid)
    if not inspect.isclass(exctype):
        exctype = type(exctype)
    res = ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, ctypes.py_object(exctype))
    if res == 0:
        raise ValueError("invalid thread id")
    elif res != 1:
        # """if it returns a number greater than one, you're in trouble,
        # and you should call it again with exc=NULL to revert the effect"""
        ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, None)
        raise SystemError("PyThreadState_SetAsyncExc failed")


def stop_thread(thread):
    """
    @profile:强制停掉线程函数
    :param thread:
    :return:
    """
    if thread == None:
        print('thread id is None, return....')
        return
    _async_raise(thread.ident, SystemExit)
Categories: Python

0 Comments

Leave a Reply

Your email address will not be published.