simple threading

Ype Kingma ykingma at accessforall.nl
Tue Oct 9 15:34:05 EDT 2001


Mark,

> 
> I am trying run a particularly processor hungry function in a
> seperate thread but I can't quite figure out how to return
> the arguments from the object now.
> 
> previously the function call was coded as:
> 
> motifs = motifFinder.findOtherOccurances(posList, doubles)
> 
> the new code is:
> 
> motifs = thread.start_new_thread(motifFinder.findOtherOccurances,\
>         (posList, doubles))
> 
> The function seems to run fine, but it always returns None,
> can anyone tell me what I am doing wrong?

thread.start_new_thread() returns immediately, without waiting for
the thread to finish.
You'll have to decide what to do with the motifs at the point where
the function returns.

In case you want to wait idle for the result there is no point in using
threads. In case you want to do sth else while the thread is running
and then wait for it's result have a look at the threading module.

Eg. you can pass the result via another object and synchronize between
the two threads using a threading.event in same object:

import threading

class ResultWaiter:
    # Warning: untested code.
    def __init__(self):
        self.resultReady = threading.event()

    def setResult(self, result):
        self.result = result
        self.resultReady.set()

    def resultAvailable(self):
        return self.resultReady.isSet()

    def waitForResult(self):
        self.resultReady.wait()
        return self.result

waiter = ResultWaiter()
thread.start_new_thread(motifFinder.findOtherOccurances,
 (posList, doubles), waiter)
# The function does waiter.setResult(motifs) instead of returning motifs

doSomethingElse()
if not waiter.resultAvailable(): doSomethingMore()

motifs = waiter.waitForResult()

> 
> TIA
> 

My pleasure,
Ype

-- 
email at xs4all.nl



More information about the Python-list mailing list