Quantcast
Channel: Raspberry Pi Forums
Viewing all articles
Browse latest Browse all 5233

Python • Re: Unknown threads running in Python application

$
0
0
Give the threads special names, so you know which function started the thread. You could also collect all threads in a list and use an Event to stop the while loop inside the worker function, which is executed by the thread. Then the thread does not stop imminently, so you should wait for the threads to finish.

If you don't wait, it blocks until all non-daemon threads are dead and after this, the main-thread finishes.
If the threads are daemon-threads, then the main-thread does not wait until they are finished (returned).

By the way, please avoid the use of global.

Example:

Code:

import timefrom random import uniformfrom threading import Event, Threaddef worker(name, stop):    """    Simulate work    """    while not stop.is_set():        # simulating random slow process        time.sleep(uniform(2, 5))    print(f"{name} left the while loop")def start(threads):    """    Start all threads.    """    for thread in threads:        thread.start()def stop(ev):    """    Set the Event to let all threads finish    """    ev.set()def wait_stopped(threads):    """    Wait until all threads are stopped.    They stop, if the target function returns.    """    while any(t.is_alive() for t in threads):        print("Waiting for threads to finish")        time.sleep(0.5)def creator(num):    ev = Event()    threads = [        Thread(target=worker, args=(f"Worker-Thread-{n}", ev), name=f"MyThread-{n}")        for n in range(num)    ]    start(threads)    return ev, threadsevent, threads = creator(10)time.sleep(2)print("Stopping threads")stop(event)wait_stopped(threads)
PS: Do not forget, that some libraries are using threads. This could be the issue, if you're sure, that all Threads in your code get names.

Statistics: Posted by DeaD_EyE — Thu Jan 09, 2025 8:28 pm



Viewing all articles
Browse latest Browse all 5233

Trending Articles