returning a value from a thread

Jeff Shannon jeff at ccvcorp.com
Wed Jul 14 14:06:34 EDT 2004


Christopher T King wrote:

>On Wed, 14 Jul 2004, Ken Godee wrote:
>
>  
>
>>I thought there was some sort of memory type container
>>I could use...
>>
>>ie. store value in memory from module3 and be able to
>>read it from module1.
>>
>>The closest I can think of is to pass a queue reference
>>and stor values from module3 in the queue and then read them
>>back while in module1.
>>    
>>
>
>Actually, any kind of container object would do: you could pass a list, 
>dictionary, or class to the thread, and the thread could store its results 
>in it.
>
>A hackish method would be to pass the dictionary returned by locals() in 
>module1 to the thread. This way the thread could set a value in module1 
>directly.
>
>Just don't forget to .join() on the thread in module1 before accessing the 
>container object! (Assuming you're using threading) I just wish Python's 
>.join() could return values, like pthread_join can.
>  
>

This may work if the worker thread will perform a relatively short task 
and then die *before* you access the result.  But lists and dictionaries 
are not thread-safe -- if they are potentially accessed by multiple 
threads concurrently, then the behavior will be unpredictable.  (Think 
of a case where thread B starts to update a dictionary, inserts a key 
but is interrupted before it can attach a value to that key, and then 
while thread B is interrupted thread A looks at the dictionary and finds 
the key it's looking for, but with no valid reference as its value... 
[Disclaimer: I don't know the inner workings of dictionaries well enough 
to know if this exact situation is possible, but I do know that dicts 
are not threadsafe, so something *similar* is possible...])

Unless you're certain that your worker thread can die before you get the 
results, and you're able to have your main thread potentially sit around 
doing nothing until that happens (which is what join() does), you need 
to use a threadsafe method of passing data back and forth.  The simplest 
such method is indeed to use a queue.  You *can* use some other 
container, and protect access to that container through the use of 
locks.... but that's exactly what a queue does, so why reinvent the wheel?

Jeff Shannon
Technician/Programmer
Credit International




More information about the Python-list mailing list