python has no ready-made method to force thread termination, so it is recommended to use the multiprocessing module instead.
< hr >
forced termination of a thread can be achieved by ctypes calling the system API. Take the windows system as an example, as follows
-sharp -*- coding: utf-8 -*-
import threading
import time
from datetime import datetime
def term_thread(thread_id):
-sharp
import os
if os.name == "nt":
-sharp windows
-sharp : threading.Thread
import ctypes
h = ctypes.windll.kernel32.OpenThread(1, 0, thread_id)
assert h != 0
r = ctypes.windll.kernel32.TerminateThread(h, 0xff)
assert r != 0
else:
-sharp TODO
raise NotImplementedError
def run_thread():
while 1:
time.sleep(1)
print('{}'.format(datetime.now()))
def main():
t = threading.Thread(target=run_thread)
t.start()
time.sleep(3)
term_thread(t.ident)
-sharp join()
-sharp t.join()
if __name__ == '__main__':
main()
Python's threading class does not provide an exit method, which needs to be implemented on its own.
this involves two issues:
-
Thread communication : how does the child thread know that the parent thread exits the child thread.
-
implementation of exit : child threads know how to exit
< H2 > Thread communication < / H2 >
threading
provides the Event
class. In fact, this class is a signal that can easily communicate between threads. Because multithreading runs in a process, you can also define a class to convey signals. Skip the table.
working
working
exiting
False
calling exit (), within a child thread is a matter of exiting the child thread instead of the main thread.
< H2 > exit thread < / H2 >
there are many ways to exit a thread, but the core is to determine the state of the signal. This requires a good judgment point in the worker process control. To make it clear that the exit is not that the instruction will be executed immediately, but that the code that processes the signal will stop the worker, only when the signal change is found, it needs to be implemented on its own.
for example, the above code jumps out of the while loop after the signal.isSet ()
has changed. In fact, worker is over. The exit
method is to increase readability, so there is no need to add it at all.
you can end the thread by any method. After running or manually exit, you can