Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return value from thread

How do I get a thread to return a tuple or any value of my choice back to the parent in Python?

like image 623
pjay Avatar asked Dec 11 '09 06:12

pjay


People also ask

Can we return value from thread in Java?

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.

How does thread call method return value?

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.

How does a thread return a value in C++?

#include <thread> #include <future> int func() { return 1; } std::future<int> ret = std::async(&func); int i = ret. get();

How do you return a value from a Posix thread?

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.


1 Answers

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 .puts 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!-)

like image 138
Alex Martelli Avatar answered Oct 06 '22 18:10

Alex Martelli