Thread confusion?

Costas Menico costas at meezon.com
Thu May 24 04:07:08 CEST 2001


Benjamin Schollnick <junkster at rochester.rr.com> wrote:

>I'm having a problem with python threading, where python is probably 
>doing EXACTLY as it was designed, but it's not what I would expect.
>
>Example:
>
>      def   run_a_thread ( value1, value2):
>         d1 = run_sub_function1 (value1)
>         d2 =run_sub_function2 (value2)
>      return d1, d2   
>
>   data = start_new_thread (run_a_thread, (v1, v2,) )
>
>Now the thread appears to start, but as far as I can tell, it runs for 
>"no time", and returns value of NONE.
>
>As I've read, the thread continues until the function that is run is 
>exited.... But run_a_thread isn't exited until after run_sub_function2 
>is finished (*In my Logical universe that is*)
>
>I'm assuming as soon as run_a_thread runs the "run_sub_function1" 
>module, run_a_thread is considered "finished", and the thread closes...

Bets way is to make a class, only because it is easier to control what
and how your functions run. Here is an example:

import thread as thr
import time
class MyClass:
    def __init__(self):
        self.completed=0
        
    def run_sub_function1(self,value):
        return value*2

    def run_sub_function2(self,value):
        return value*4
                
    def run_a_thread (self, value1, value2):
        self.d1 = self.run_sub_function1(value1)
        self.d2 = self.run_sub_function2(value2)
        self.completed =1

# Main program
anObj=MyClass()
# Start thread
thr.start_new_thread (anObj.run_a_thread, (1, 2) )
# Wait for completion by polling a flag.
while not anObj.completed:
    time.sleep(0.001)
    print "Waiting"
print "Done", anObj.d1, anObj.d2

Costas



More information about the Python-list mailing list