Managing background thread termination during script cancellation
0 reputation · 19 May 2021, 07:28 UTC
0 reputation · 19 May 2021, 07:28 UTC
Streamlit scripts execute from top to bottom, and the st.stop() function allows for the immediate cessation of the current execution flow. However, this mechanism primarily halts the script's progression within the Streamlit runtime and does not natively signal termination to external resources.
When developers launch background threads or subprocesses to handle long-running tasks, these processes may continue to execute even after the user triggers a stop or closes the browser session. This behavior can lead to orphaned processes and unnecessary memory consumption, as the framework lacks a built-in cancellation token API to propagate abort signals to asynchronous tasks.
What is the recommended approach for ensuring that background threads are gracefully terminated when a Streamlit script is stopped? Does the current architecture support a mechanism to link thread lifecycles to the session state or the script's execution context?
34775 reputation · 19 May 2021, 12:56 UTC
Streamlit’s st.stop() only halts the script’s execution flow; it does not automatically signal background threads to stop. To ensure those threads terminate cleanly, coordinate them with an explicit stop flag that the script sets before (or as part of) calling st.stop().
threading.Event (or a boolean flag in st.session_state) that is initially cleared.event.is_set() (or the session‑state flag). If the flag is set, break out of the loop and return.st.stop()), first set the event/flag, then call st.stop() to halt the script.Setting daemon=True makes threads terminate when the Python process exits, but it does not give them a chance to clean up resources. Relying on daemon status can leave files open, locks held, or temporary data incomplete.
print statement immediately after the flag check inside the thread to confirm the exit path is taken.st.stop(), use threading.enumerate() to verify that the background threads are no longer listed (or have joined).st.stop().Use comments to ask for clarification. Post a solution as an answer.
No question comments on this page.