Re: Passing functions as parameter (multiprocessing)

Discussion in 'Python' started by Peter Otten, Nov 13, 2012.

  1. Peter Otten

    Peter Otten Guest

    Jean-Michel Pichavant wrote:

    > I'm having problems understanding an issue with passing function as
    > parameters.


    > Here's a code that triggers the issue:
    >
    >
    > import multiprocessing
    >
    > def f1():
    > print 'I am f1'
    > def f2(foo):
    > print 'I am f2 %s' % foo
    >
    > workers = [
    > (f1,tuple()),
    > (f2,(5,)),
    > ]
    >
    > procs=[]
    > for func, parameters in workers:


    > def subproc(*args, **kwargs):
    > return func(*args, **kwargs)
    > procs.append(multiprocessing.Process(target=subproc, args=parameters))


    Python has late binding, and when the loop has finished the name func is
    bound to f2. You have created multiple subproc functions, but that doesn't
    matter as they all invoke func aka f2.

    A possible fix:

    def make_subproc(func):
    def subproc(*args, **kwargs):
    return func(*args, **kwargs)
    return subproc

    procs=[]
    for func, parameters in workers:
    procs.append(multiprocessing.Process(target=make_subproc(func),
    args=parameters))
    Peter Otten, Nov 13, 2012
    #1
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Metalone
    Replies:
    0
    Views:
    333
    Metalone
    Jan 6, 2010
  2. Mister B
    Replies:
    8
    Views:
    530
    Nick Keighley
    Aug 26, 2010
  3. MRAB
    Replies:
    0
    Views:
    188
  4. Oscar Benjamin
    Replies:
    0
    Views:
    151
    Oscar Benjamin
    Nov 13, 2012
  5. Peter Otten
    Replies:
    0
    Views:
    183
    Peter Otten
    Nov 13, 2012
Loading...

Share This Page