Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python threading on close callback [duplicate]

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

like image 722
Sony Nguyen Avatar asked May 08 '16 21:05

Sony Nguyen


People also ask

Do Python threads close themselves?

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.

How do you close the current thread in Python?

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.

Are callbacks threaded?

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.

How do you use multiple threads in Python?

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.


1 Answers

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.

like image 97
Rushy Panchal Avatar answered Nov 16 '22 14:11

Rushy Panchal