How do I get a thread to return a tuple or any value of my choice back to the parent in Python?
The thread that needs to return the value uses the Callable interface to implement the call method; Before getting the future object, you can use the isDone() method to check whether the future is complete. After that, you can call the get() method to get the value of the future.
ThreadStart delegates in C# used to start threads have return type 'void'. If you wish to get a 'return value' from a thread, you should write to a shared location (in an appropriate thread-safe manner) and read from that when the thread has completed executing.
#include <thread> #include <future> int func() { return 1; } std::future<int> ret = std::async(&func); int i = ret. get();
If you want to return only status of the thread (say whether the thread completed what it intended to do) then just use pthread_exit or use a return statement to return the value from the thread function.
I suggest you instantiate a Queue.Queue before starting the thread, and pass it as one of the thread's args: before the thread finishes, it .put
s the result on the queue it received as an argument. The parent can .get
or .get_nowait
it at will.
Queues are generally the best way to arrange thread synchronization and communication in Python: they're intrinsically thread-safe, message-passing vehicles -- the best way to organize multitasking in general!-)
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