stop thread from outside 'run'

MRAB python at mrabarnett.plus.com
Tue Jun 5 12:59:34 EDT 2012


On 05/06/2012 09:11, Prashant wrote:
> Hi,
>
> I am using tornado web socket server to communicate between python(server) and browser(client). To mimic the behavior of sending data to client and get results back, I am using threaded approach:
>
> class JobThread(threading.Thread):
>      """"""
>      def __init__(self, target):
>          """"""
>          super(JobThread, self).__init__()
>          self.target = target
>          self.res = None
>          self.stoprequest = threading.Event()
>          self.start()
>          self.join()
>          # Execution stops here and wait
>          return self.result()
>
>      def run(self):
>          """ Start this thread """
>          self.target()
>          while not self.stoprequest.isSet():
>              print "running..."
>
>      def result(self):
>          """"""
>          return self.res
>
>      def kill(self, result):
>          """ Kill this thread """
>          self.res = result
>          self.stoprequest.set()
>
> def ReceiveData(message):
>      """"""
>      global t
>      print str(message)
>      t.kill(message)
>
> def SendData(data_string):
>      """"""
>      sendMessageWS(data_string)
>
> result = JobThread(partial(SendData, data_string))
>
JobThread is a class, so a statement of the form:

     result = JobThread(...)

will simply create an instance of the JobThread class and then bind it
to the name "result".

The __init__  method is called to initialise the instance; any value
returned the method will be discarded.

> As soon as jobThread instance starts it sends data to websocket and wait for client to response. Client is sending back results but 'ReceiveData' is not getting called because of infinite loop in 'run' method. The only way you can stop the thread is from outside when "ReceiveData" executes and kill the threaded instance 't'.
>
> Any pointers?




More information about the Python-list mailing list