How do the child threads and processes of Python end manually?

  • 2021-11-13 08:15:50
  • OfStack

How to End Subthreads and Subprocesses of Python

Method to end child threads:

This is the code of carrying other great gods. I don't know the principle. Anyway, I didn't find any shortcomings for the time being. Let's talk about it first.


import inspect
import ctypes
import threading
from time import sleep
 
 
def serial_read():
 
    while True:
 
        print(" Brother Chun is a pure man! ")
 
        sleep(1)
 
 
 
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 Air():
 
    ords=0
 
    myThread = threading.Thread(target=serial_read)
 
    myThread.start()
 
    while True:
 
 
        ords+=1
 
        if ords==10:
 
            stop_thread(myThread)
            print(" Stop a child thread ")
            break
 
 
        sleep(1)
 
 
if __name__ == '__main__':
 
    Air()

Here is how to end a child process:


import inspect
import ctypes
from time import sleep
from multiprocessing import Process
 
 
def serial_read():
 
    while True:
 
        print(" Brother Chun is a pure man! ")
 
        sleep(1)
 
 
def Air():
 
    ords=0
 
    myThread = Process(target=serial_read)
 
    myThread.start()
 
    while True:
 
 
        ords+=1
 
        if ords==10:
 
            myThread.terminate()
            print(" Stop child process ")
            break
 
 
        sleep(1)
 
 
if __name__ == '__main__':
 
    Air()

Here, let's say how to write if we use classes. To end a child process or thread, you need to get the process object or thread object. However, there is no way to create a class property in a class and then call it in other class methods in the way of self. × × ×. At this time, create a class attribute list, then create a sub-process or sub-thread, assign the object to this list, and then call the elements in this list in other methods of the class, and get the object of the sub-process or sub-thread.

For example:


def startss(self,a1,b1,c1,under,rough,blue,among):
 
        #  Create a new thread 
        p1=threading.Thread(target=self.line01,args=(a1,b1,under,rough,)) # Must be added , No.  
        p2=threading.Thread(target=self.line02,args=(a1,c1,under,blue,))
        p3=Process(target=self.Process01,args=(under,rough,blue,)) # Computing process 
 
        #among Is a class attribute list Container 
 
        among.append(p1)
        among.append(p2)
        among.append(p3)
 
        #  Open a new thread 
        p1.start()
        p2.start()
 
        # Start the computing process 
        p3.start()

Reference: https://www.ofstack.com/article/185867. htm

python How Multiprocess Terminates or Restarts Child Processes


Related articles: