You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

  1. Use the run() Method for Thread Logic:
    Since LEDManager inherits from threading.Thread, we override the run() method—this is the standard entry point for thread execution. When you call start() on a thread instance, it automatically runs run() in a separate thread.

  2. Correct Thread Instance Creation:
    Instead of manually creating threading.Thread objects pointing to a standalone method, we just instantiate our LEDManager class (which is already a Thread subclass). This keeps the code organized and follows Python's threading conventions.

  3. 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 inside run(), which only triggers when start() is called—so all threads are created first before any of them begin their loops.

  4. Expand to 50 Threads Easily:
    Just change thread_ids = range(2) to thread_ids = range(50)—the loop will create 50 separate LEDManager threads, 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 08:10:40