@@ -16,6 +16,7 @@ class StopCoroutineException( Exception ):
1616
1717class Coroutine ( threading .Thread ):
1818 def __init__ (self , func , * args , ** kwargs ):
19+ print "Coroutine: %r %r" % (args , kwargs )
1920 threading .Thread .__init__ (self )
2021 self .args = args
2122 self .kwargs = kwargs
@@ -48,17 +49,20 @@ def run(self):
4849 exc_type , exc_value , exc_traceback = sys .exc_info ()
4950 trace = "" .join (traceback .format_tb (exc_traceback ))
5051 self .logger .debug ( "Traceback (latest call first):\n %s" % trace )
52+ self .stopEvent .set () # Need to tell caller to do a join.
5153 self .callerSemaphore .release ()
5254 threading .Thread .run (self ) # Does some cleanup.
5355
5456 def call (self , param = None ):
5557 '''Executed from the caller thread. Runs the coroutine until it calls wait.
5658 Does nothing if the thread has terminated.
5759 If a parameter is passed, it is returned from the Coroutine.wait() function in the coroutine thread.'''
58- if self .isAlive ():
60+ if self .is_alive ():
5961 self .callParam = param
6062 self .mySemaphore .release ()
6163 self .callerSemaphore .acquire ()
64+ if self .stopEvent .is_set ():
65+ self .join () # Ensure that is_alive is false on exit.
6266 return self .callResult
6367
6468 def stop (self ):
@@ -85,12 +89,27 @@ def wait(param = None):
8589
8690 @staticmethod
8791 def waitMilliseconds (timeMillis ):
88- 'Called from within the coroutine to wait the given time'
92+ '''Called from within the coroutine to wait the given time.
93+ I.e. Invocations of the coroutine using call() will do nothing until then. '''
8994 startTime = Coroutine .currentTimeMillis ()
9095 while Coroutine .currentTimeMillis () - startTime < timeMillis :
9196 Coroutine .wait ()
9297
93- # while not self.stopEvent.is_set():
98+ @staticmethod
99+ def runTillFirstCompletes (* coroutines ):
100+ def runTillFirstCompletesFunc (* coroutineList ):
101+ while True :
102+ for c in coroutineList :
103+ c .call ()
104+ if not c .is_alive ():
105+ break
106+ Coroutine .wait ()
107+ for c in coroutineList :
108+ if c .is_alive ():
109+ c .stop ()
110+
111+ result = Coroutine (runTillFirstCompletesFunc , * coroutines )
112+ return result
94113
95114#
96115# self.scheduler.coroutines.remove( self )
0 commit comments