Get help from the marimo community

Updated 4 weeks ago

threading

Hello, i want to use a long living thread in my notebook. I dumbed it down to this basic example:
Plain Text
import threading
import time
threading.Thread = mo.Thread

def run_long():
    while True:
        print("looping")
        time.sleep(1)

bar = threading.Thread(target=run_long)
bar.start()


When i run this cell, looping is only printed once (it looks like the while loop stop after one iteration).
M
S
k
6 comments
hmm that seems like a bug. I see it printing out to my terminal, but not the marimo output. we can look into fixing this.
we can look into this. out of curiosity, what are you looking to do with the thread? e.g. pull data, refresh, etc.
not sure if this solves your issue, but a bar.join() could help. The output would be kept in the cell / different cell.
We want to give scientists the ability to start a seperate process (in our case, start capturing images from a camera) and stop it with a click on a button.

Using bar.join() worked, thanks!
update

After some searching, I found the problem lies in the use of time.sleep() in a thread. The thread seems to stop after a time.sleep()
Plain Text
import threading
import time

# Override the Thread class with a custom Thread class
threading.Thread = mo.Thread

def run_thread_with_sleep():
    print("bar")
    time.sleep(2)
    print("foo")
        
# Create a new thread that runs the function
foo = threading.Thread(target=run_thread_with_sleep)
foo.start()


This code prints bar but not foo
there was another issue about this. we've identified the fix and a contributor is helping out fixing it. (the thread is still running, but the stdio does get detached)
Add a reply
Sign up and join the conversation on Discord