executing multiple functions in background simultaneously

Catherine Moroney Catherine.M.Moroney at jpl.nasa.gov
Thu Jan 15 00:50:54 CET 2009


James Mills wrote:
> On Wed, Jan 14, 2009 at 11:02 AM, Catherine Moroney
> <Catherine.M.Moroney 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.
>> Currently I'm doing this by calling them as sub-processes
>> executable from the command-line.  Is there a way of accomplishing
>> the same thing without having to make command-line executables
>> of the function call?
> 
> 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.
> 
> pydoc threading.Thread
> 
> cheers
> James

What is the proper syntax to use if I wish to return variables
from a function run as a thread?

For example, how do I implement the following code to return
the variable "c" from MyFunc for later use in RunThreads?
Trying to return anything from the threading.Thread call results
in a "unpack non-sequence" error.

import threading, sys

def MyFunc(a, b):

     c = a + b
     print "c =",c
     return c

def RunThreads():

     args = (1,2)
     threading.Thread(target=MyFunc,args=(1,2)).start()

if __name__ == "__main__":

     RunThreads()

     sys.exit()




More information about the Python-list mailing list