python thread child thread exits and exit control code

@ This article comes from public number: csdn2299, like the number of programmers can focus on public institutions

This article introduces the child thread exits python code and the thread exit control, very good, has a certain value for references, a friend in need can refer
to introduce the following python problem child thread exit code, shown below :

def thread_func():
  while True:
      #do something
      #do something
      #do something
t=threading.Thread(target = thread_func)
t.start()
# main thread do something
# main thread do something
# main thread do something

Run up is no problem, but when using ctrl + c interrupt problem, the main thread exits, but the child thread is still running.

Thus an increase in the main thread code signal processing, change the child thread loop condition upon receipt sigint

loop = True
def thread_func():
  while loop:
      #do something
      #do something
      #do something
t=threading.Thread(target = thread_func)
t.start()
# ctrl+c时,改变loop为False
def handler(signum, frame):
  global loop
  loop = False
  t.join()
  exit(0)
signal(SIGINT, handler)
# main thread do something
# main thread do something
# main thread do something

Such ctrl + c to exit, but doubt that the main thread exits the process will not quit?

Python thread exit point spread knowledge control

ctypes module control thread exit

Python threading module and there is no mechanism in the design of the thread exits, the reason is not normal either a thread exit may lead to unintended consequences.

E.g:

The thread is holding a resource must release the correct key, lock.

Child thread thread creation, but also it will be killed.

Management own thread, the best approach is to have a request for exit signs, so that each thread based on certain time intervals to check the rules to see whether they need to quit.

For example the following code:

import threading
class StoppableThread(threading.Thread):
  """Thread class with a stop() method. The thread itself has to check
  regularly for the stopped() condition."""
 
  def __init__(self):
    super(StoppableThread, self).__init__()
    self._stop_event = threading.Event()
 
  def stop(self):
    self._stop_event.set()
 
  def stopped(self):
    return self._stop_event.is_set()

The code inside the thread should periodically check the stop sign, at the time of exit, you can call the stop () function, and use the join () function to wait for a thread to exit.

However, there may be circumstances really want to kill the thread, for example, you are an external library package, calling it busy for a long time, and you want to break it.

Python threads can throwing an exception:

Parameter passing are the thread id number and withdraw identification

def _async_raise(tid, exctype):
  '''Raises an exception in the threads with id tid'''
  if not inspect.isclass(exctype):
    raise TypeError("Only types can be raised (not instances)")
  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, 0)
    raise SystemError("PyThreadState_SetAsyncExc failed")

If the threads running outside the python interpreter, it will not capture interrupt that throws an exception, the thread can not be interrupted.

After simplification, the above code can be applied to practical use in an interrupt to a thread, the thread running frequently detected, for example over itself tolerable range.

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)

Thank you very much to read
in college chose the self-python, found that eating a working computer basic bad loss, this is not educated
can not do, can only be acquired to make up, then opened his own counter-attack outside the coding road, constantly learning python core knowledge, in-depth knowledge of basic computer learning, organized, if you are unwilling to mediocrity, it is with me outside of coding, growing it!
In fact, there is not only technical, more technical stuff than those, for example, how to make a fine programmer, rather than "Cock wire", the programmer itself is a noble presence, ah, is not it? [Click to join] want you want to be a noble person, refueling

Published 61 original articles · won praise 22 · views 40000 +

Guess you like

Origin blog.csdn.net/haoxun02/article/details/105316592