Home  >  Article  >  Backend Development  >  How to close a thread in python

How to close a thread in python

coldplay.xixi
coldplay.xixiOriginal
2021-03-02 15:58:4619320browse

How to close a thread in python: first import threading and define a method; then define the thread, target points to the method to be executed, start it; finally stop the thread, the code is [stop_thread(myThread)].

How to close a thread in python

The operating environment of this tutorial: Windows 7 system, python version 3.9, DELL G3 computer.

How to close threads in Python:

1. Start threads

First import threading

import threading

Then define a method

    def serial_read():
   ...
   ...

Then define the thread, the target points to the method to be executed

myThread = threading.Thread(target=serial_read)

Start it

myThread.start()

2. Stop the thread

Not much to say, just go to the code

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)

Stop the thread

stop_thread(myThread)

Related free learning recommendations: python video tutorial

The above is the detailed content of How to close a thread in python. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn