executing multiple functions in background simultaneously

Aaron Brady castironpi at gmail.com
Wed Jan 14 19:36:25 EST 2009


On Jan 14, 6:00 pm, Cameron Simpson <c... at zip.com.au> wrote:
> On 14Jan2009 15:50, Catherine Moroney <Catherine.M.Moro... at jpl.nasa.gov> wrote:
>
> > James Mills wrote:
> >> On Wed, Jan 14, 2009 at 11:02 AM, Catherine Moroney
> >> <Catherine.M.Moro... at jpl.nasa.gov> wrote:
> >>> I would like to spawn off multiple instances of a function
> >>> and run them simultaneously and then wait until they all complete.
> [...]
> >> Try using the python standard threading module.
> >> Create multiple instances of Thread with target=your_function
> >> Maintain a list of these new Thread instnaces
> >> Join (wait) on them.
>
> > What is the proper syntax to use if I wish to return variables
> > from a function run as a thread?
>
> The easy thing is to use a Queue object. The background thread uses
> .put() to place a computed result on the QUeue and the caller uses
> .get() to read from the queue. There's an assortment of other ways too.

You could just set the result as an attribute of the thread you're
starting (untested):

class MyThread(Thread):
  def run( self ):
    stuff()
    self.result= something

(Strictly speaking, threads don't return values, since nothing follows
them in flow of control.)



More information about the Python-list mailing list