On 04/18/2015 01:07 PM, D. Xenakis wrote:
Maybe this is pretty simple but seems I am stuck...

def message_function():
     return "HelloWorld!"


def thread_maker():
     """
     call message_function()
     using a new thread
     and return it's "HelloWorld!"
     """
     pass


Could someone please complete above script so that:

thread_maker() == "HelloWorld!"

Please import the library you suggest too.
I tried threading but I could not make it work.

THX!


The first question is why you are even starting extra threads. They are only useful if they do concurrent work. So if you're starting a thread, then not doing anything yourself till the thread terminates, you've gained absolutely nothing. And greatly complicated your code besides.

In fact, even if you start multiple threads, and/or continue doing your own work in the main thread, you might not gain anything in CPython, because of the GIL.

But if I assume you've justified the use of threads, or your boss/instructor has mandated them, then you still have to decide what the flow of logic is going to mean.

If you're going to start a bunch of threads, wait a while, and do something with the "return values" of some subset of them, then all you need is a way to tell whether those threads have yet posted their results. If there's exactly one result per thread, then all you need is a global structure with room for all the results, and with an initial value that's recognizably different.

So fill a list with None elements, and tell each thread what element of the list to update. Then in your main thread, you trust any list element that's no longer equal to None.

Alternatively, you might decide your main program will wait till all the threads have terminated. In that case, instead of checking for None, simply do a join on all the threads before using the results.

But many real threaded programs use much more complex interactions, and they reuse threads rather than expecting them to terminate as soon as one result is available. So there might not be a single "result" per thread, and things get much more complex. This is where you would normally start studying queues.


--
DaveA
--
https://mail.python.org/mailman/listinfo/python-list

Reply via email to