python daemon 含义

daemon = True, 看成是后台线程,False 为前台线程, 同C# 前后台线程一个含义,同java;
参考别人博客:https://laike9m.com/blog/daem...,97/
  • 当 python 所有的前台线程都结束时,进程退出, 不管是否还有后台线程;
  • 后台线程一般做心跳,主线程结束时,也就没了意义;
  • 主线程默认时前台线程, 创建子线程时,子线程的daemon 参数继承父线程;

gevent 中 daemon 的场景;

  • gevent.spawn 创建的协程都是后台协程,也就是daemon = True;
  • 通过gevent.patch 的threading.Thread 的daemon = False 的协程,是前台协程;

python 干掉协程的方式:

gevent.kill

python3 杀掉线程的方式

参考链接:https://www.geeksforgeeks.org...
  • Raising exceptions in a python thread

    import threading
    import time
    import inspect
    import ctypes
    
    
    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):
    _async_raise(thread.ident, SystemExit)
    
    
    def test():
    while True:
        print('-------')
        time.sleep(0.5)
    
    
    if __name__ == "__main__":
    t = threading.Thread(target=test)
    t.start()
    time.sleep(5.2)
    print("main thread sleep finish")
    stop_thread(t)
  • Set/Reset stop flag
  • Using traces to kill threads

    import sys
    import trace
    import threading
    import time
    class thread_with_trace(threading.Thread):
      def __init__(self, *args, **keywords):
          threading.Thread.__init__(self, *args, **keywords)
          self.killed = False
    
      def start(self):
          self.__run_backup = self.run
          self.run = self.__run     
          threading.Thread.start(self)
    
      def __run(self):
          sys.settrace(self.globaltrace)
          self.__run_backup()
          self.run = self.__run_backup
    
      def globaltrace(self, frame, event, arg):
          if event == 'call':
              return self.localtrace
          else:
              return None
    
      def localtrace(self, frame, event, arg):
          if self.killed:
              if event == 'line':
                  print('line exit')
                  raise SystemExit()
          return self.localtrace
    
      def kill(self):
          self.killed = True
    
    
    def func():
      while True:
          print('thread running')
          time.sleep(1)
    
    t1 = thread_with_trace(target = func)
    t1.start()
    time.sleep(2)
    t1.kill()
    t1.join()
    if not t1.isAlive():
      print('thread killed')
    
  • Using the multiprocessing module to kill threads
  • Killing Python thread by setting it as daemon
  • Using a hidden function _stop(), 此方法无效

zed2015
15 声望2 粉丝