Quantcast
Channel: Active questions tagged python - Stack Overflow
Viewing all articles
Browse latest Browse all 23131

How to stop a running thread in the background

$
0
0
import threadingthreading.enumerate()Out[9]: [<_MainThread(MainThread, started 15492)>,<Thread(IOPub, started daemon 15324)>,<Heartbeat(Heartbeat, started daemon 15964)>,<ControlThread(Control, started daemon 14072)>,<HistorySavingThread(IPythonHistorySavingThread, started 13076)>,<Thread(Thread-5 (poll_thread), started 12664)>,<ParentPollerWindows(Thread-4, started daemon 16068)>,<Thread(Thread-7 (AutoReloginTimer), started 15576)>,<Thread(Thread-8 (Websocket1_connect), started 10780)>]

I need to stop these background threads, but I lack information about their origin or starting points.help me please!!

import threadingimport time# Define a thread subclassclass MyThread(threading.Thread):    def __init__(self):        super(MyThread, self).__init__()        self.stop_flag = False  # Flag to indicate whether the thread should stop    def run(self):        while not self.stop_flag:            print("Thread {} is running...".format(threading.current_thread().name))            time.sleep(1)        print("Thread {} stopped.".format(threading.current_thread().name))    def stop(self):        self.stop_flag = True  # Set the flag to stop the thread# Create multiple instances of the threadthreads = [MyThread() for _ in range(5)]# Start all threadsfor thread in threads:    thread.start()# Let the threads run for a few secondstime.sleep(5)# Stop all threadsfor thread in threads:    thread.stop()# Wait for all threads to finishfor thread in threads:    thread.join()print("Main program finished.")

I attempted to address the issue with ChatGPT, but unfortunately, it did not resolve my problem.?


Viewing all articles
Browse latest Browse all 23131

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>