Python多线程无限循环问题:复用单类创建多线程仅一个运行
Hey there, let's break down why your code isn't working and fix it step by step.
First, the main issue is how you're creating your threads. When you write target=LEDManager.initiate(led_index), you're directly calling the initiate function right there in the main thread instead of passing it as a callable to the thread. Since initiate is an infinite loop, your main thread gets stuck running that first call forever—never getting around to creating or starting the other threads.
On top of that, your LEDManager class inherits from threading.Thread but doesn't use the standard run() method, which is what the Thread class expects to execute when you start the thread. Your initiate method also isn't set up correctly as either an instance method (missing self) or a static method.
Let's fix this properly:
Fixed Code
import threading import time class LEDManager(threading.Thread): def __init__(self, id_manager): super().__init__() # Cleaner way to call the parent class constructor self.id_manager = int(id_manager) def run(self): # This method automatically runs when the thread starts while True: print(f"Thread {self.id_manager} blink on") time.sleep(2) print(f"Thread {self.id_manager} blink off") time.sleep(2) def main(): # Test with 2 threads first, expand to 50 by changing range(2) to range(50) thread_ids = range(2) thread_list = [] # Create all thread instances first for thread_id in thread_ids: led_thread = LEDManager(thread_id) thread_list.append(led_thread) # Optional sleep here if you want to stagger thread start times # Start all threads simultaneously for thread in thread_list: thread.start() # Optional: If you need the main thread to wait for all threads (they run infinitely, so this blocks forever) # for thread in thread_list: # thread.join() if __name__ == "__main__": main()
Key Fixes Explained
Use the
run()Method for Thread Logic:
SinceLEDManagerinherits fromthreading.Thread, we override therun()method—this is the standard entry point for thread execution. When you callstart()on a thread instance, it automatically runsrun()in a separate thread.Correct Thread Instance Creation:
Instead of manually creatingthreading.Threadobjects pointing to a standalone method, we just instantiate ourLEDManagerclass (which is already a Thread subclass). This keeps the code organized and follows Python's threading conventions.Avoid Directly Executing the Infinite Loop:
In your original code,LEDManager.initiate(led_index)ran immediately in the main thread, blocking all further execution. Now the infinite loop lives insiderun(), which only triggers whenstart()is called—so all threads are created first before any of them begin their loops.Expand to 50 Threads Easily:
Just changethread_ids = range(2)tothread_ids = range(50)—the loop will create 50 separateLEDManagerthreads, each running its own independent infinite loop for controlling LED strip modes.
Why Your Original Code Only Ran One Thread
When you wrote target=LEDManager.initiate(led_index), Python evaluated that function call right away. Since initiate is an infinite loop, your main thread never moved past the first iteration of the for loop. It was stuck running the first thread's logic directly, not in a separate thread.
With the fixed code, you'll see all threads printing their blink messages alternately (thread execution order is non-deterministic, so output might look a bit out of order—which is normal for threads!).
内容的提问来源于stack exchange,提问作者AntonRight

