I want to run a code concurrently with streamlit, i’m trying to use threads, and I’m getting this error: 2022-08-19 08:09:33.852 Thread 'Thread-11': missing ScriptRunContext
Code:
from pathlib import Path
from threading import Thread
def target():
st.text(c)
if __name__ == '__main__':
if not st.session_state.get("thread"):
st.session_state["thread"] = True
t = Thread(target=target)
t.start()
Can you please help ? What is the best solution to use concurrency with streamlit?
Here’s what I did to get threading working correctly – you were right with the context stuff, it just looks like you didn’t start it low enough in the call stack:
import queue
import threading
import streamlit as st
from streamlit.runtime.scriptrunner import add_script_run_ctx
from streamlit.runtime.scriptrunner.script_run_context import get_script_run_ctx
def thread_task(ctx, in_q, out_q):
'''
this runs in a thread, needs a context
'''
add_script_run_ctx(ctx) # register context on thread func
while not in_q.empty():
job = in_q.get()
result = do_stuff(job)
out_q.put(result)
in_q.task_done()
def run_in_parallel(iterable, func, n_threads=10):
'''
not running in a thread; running in main context, spawns threads.
'''
ctx = get_script_run_ctx() # create a context
job_q = queue.Queue()
for thing in iterable:
job_q.put(thing)
out_q = queue.Queue()
for _ in range(n_threads):
# pass context to thread
threading.Thread(target=thread_func, args=(ctx, job_q, out_q), daemon=True).start()
in_q.join()
...
Thanks for stopping by! We use cookies to help us understand how you interact with our website.
By clicking “Accept all”, you consent to our use of cookies. For more information, please see our privacy policy.
Cookie settings
Strictly necessary cookies
These cookies are necessary for the website to function and cannot be switched off. They are usually only set in response to actions made by you which amount to a request for services, such as setting your privacy preferences, logging in or filling in forms.
Performance cookies
These cookies allow us to count visits and traffic sources so we can measure and improve the performance of our site. They help us understand how visitors move around the site and which pages are most frequently visited.
Functional cookies
These cookies are used to record your choices and settings, maintain your preferences over time and recognize you when you return to our website. These cookies help us to personalize our content for you and remember your preferences.
Targeting cookies
These cookies may be deployed to our site by our advertising partners to build a profile of your interest and provide you with content that is relevant to you, including showing you relevant ads on other websites.