Python线程while循环停止及日志不输出问题求助
Hey there! Let's tackle your two issues one by one—missing logs from your TransmitThread and old threads stopping unexpectedly when stored in a dictionary. Based on your code structure, here’s what I suggest:
The most likely culprits here are unbuffered print statements or misaligned logging configurations with Flask. Here’s how to fix it:
- Replace
print()with Python’sloggingmodule: Print statements in background threads often get buffered or ignored by Flask’s default logging setup. Swap yourprint()calls withlogging.info(),logging.debug(), orlogging.error()to integrate with Flask’s logging system. For example:import logging class TransmitThread(threading.Thread): def run(self): logging.info("Transmit thread started successfully") # ... your transmission logic ... logging.debug("Sending data to USRP device") - Configure Flask’s logging level: Make sure Flask’s logger is set to capture the level of logs you’re generating. Add this when initializing your app:
from flask import Flask import logging app = Flask(__name__) # Set to DEBUG to capture all log levels, adjust as needed app.logger.setLevel(logging.DEBUG) # Optional: Add a formatter for clearer logs logging.basicConfig(format='%(asctime)s - %(threadName)s - %(levelname)s - %(message)s') - Force flush if sticking with
print(): If you prefer to keep usingprint(), addflush=Trueto every call to bypass output buffering:print("Transmission in progress", flush=True)
Threads stopping without being explicitly told usually stems from uncaught exceptions, thread-safety issues with your stop flag, or Flask’s process/thread isolation. Let’s break down fixes:
Catch exceptions in the thread’s
run()method: If an error occurs (e.g., USRP device disconnects, IO failure), the thread will crash silently without logging. Wrap your transmission logic in a try-except block to capture and log errors:class TransmitThread(threading.Thread): def run(self): try: while not self.stop_event.is_set(): # ... your transmission logic ... except Exception as e: # Log the full error traceback for debugging logging.error(f"Thread crashed unexpectedly: {str(e)}", exc_info=True) finally: logging.info("Thread exited gracefully")Use a thread-safe stop flag instead of a boolean: Your
thdRunningboolean isn’t thread-safe—race conditions can cause the thread to miss the stop signal. Replace it withthreading.Event(), which is designed for cross-thread communication:import threading class TransmitThread(threading.Thread): def __init__(self): super().__init__() self.stop_event = threading.Event() # Thread-safe flag def run(self): logging.info("Thread started") while not self.stop_event.is_set(): # ... keep transmitting ... logging.info("Thread stopped") def stop(self): self.stop_event.set() # Safely signal the thread to stopFix Flask’s thread/process isolation for your thread dictionary: If you’re running Flask with
threaded=Trueor multiple processes, the dictionary storing your threads might not be shared across all requests.- For single-threaded/single-process development (default
app.run()), ensure your dictionary is a global variable initialized once outside request handlers. - For multi-process setups, use a shared dictionary from
multiprocessing.Manager()to ensure all processes access the same thread references:from multiprocessing import Manager # Initialize shared dictionary once before starting the app thread_store = Manager().dict() @app.route('/start-thread', methods=['POST']) def start_thread(): new_thread = TransmitThread() thread_store["active_thread"] = new_thread new_thread.start() return {"status": "started"}
- For single-threaded/single-process development (default
Verify thread references aren’t being garbage collected: Ensure your dictionary isn’t being reinitialized or cleared accidentally. Keep it as a top-level variable in your Flask app file, not inside a request handler or function that gets re-run.
Start with fixing the logging first—once you can see what’s happening inside the thread, debugging why it stops will be much easier!
内容的提问来源于stack exchange,提问作者Sagar

