I have Thread and I want to do change some flags when it finish. For example:
import threading
def on_done():
# do some printing or change some flags
def worker():
# do some calculations
t = threading.Thread(target=worker, on_close=on_done)
t.start()
But i was unable to find method like that. Any ideas how could I manage it somehow? The worker function is in separet file, so it does not know abou the flags.
Thaks in advance
Daemon Threads In computer science, a daemon is a process that runs in the background. Python threading has a more specific meaning for daemon . A daemon thread will shut down immediately when the program exits.
We can close a thread by returning from the run function at any time. This can be achieved by using the “return” statement in our target task function. If the threading. Thread class has been extended and the run() function overridden, then the “return” statement can be used in the run() function directly.
One pattern for performing long-running tasks without blocking the main thread is callbacks. By using callbacks, you can start long-running tasks on a background thread. When the task completes, the callback, supplied as an argument, is called to inform your code of the result on the main thread.
To use multithreading, we need to import the threading module in Python Program. A start() method is used to initiate the activity of a thread. And it calls only once for each thread so that the execution of the thread can begin.
One option is to simply wrap the worker function:
def wrapped_worker():
worker()
on_done()
Then, set the target to wrapped_worker
:
t = threading.Thread(target=wrapped_worker, on_close=on_done)
See this answer for a more in-depth example.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With