How to close a thread in python

coldplay.xixi
Release: 2023-01-03 09:26:59
Original
19377 people have browsed it

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
Copy after login

Then define a method

    def serial_read():
   ...
   ...
Copy after login

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

myThread = threading.Thread(target=serial_read)
Copy after login

Start it

myThread.start()
Copy after login

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)
Copy after login

Stop the thread

stop_thread(myThread)
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template