Threading question

Jp Calderone exarkun at divmod.com
Fri Apr 22 14:26:52 EDT 2005


On 22 Apr 2005 11:14:48 -0700, codecraig <codecraig at gmail.com> wrote:
>If i have a class such as
>
>class Foo:
>    def doSomething(self, cmd, cmd2, callback):
>        cmd = <translate command>
>        results = <..do some possibly long task..>
>        callback(results)
>
>What I am looking to do is have that "long task" done in a separate
>thread...how can I do this?
>
>I was thinking..
>
>class MyThread(Thread):
>    def __init__(self, cmd, cmd2, callback):
>        self.__cmd = cmd
>        self.__cmd2 = cmd2
>        self.__callback = callback
>
>    def run(self):
>        # do stuff here
>        self.__callback(some_results)
>
>...anyhow, this just didnt seem good.  I felt like i either had to pass
>MyThread a bunch of arguments it needed to run the long task, or i
>would end up passing it a 'master'...but then in MyThread I'd have
>
>self.__master.__service.execute_cmd(self.__cmd)
>
>...in java I would just create an inner class..but i am not sure
>how/what to do in python.

  Here is an implementation of this idea:

http://cvs.twistedmatrix.com/cvs/trunk/twisted/internet/threads.py?view=markup&rev=11450&root=Twisted

  Note that it uses Deferreds instead of bare callbacks (because Deferreds are better in pretty much all cases), but it is a simple matter to adapt to a bare callback API.

  Jp



More information about the Python-list mailing list