Mike5298
Mike5298

Reputation: 385

How can use the Process class of Pythons Multiprocessing library to run a function multiple times?

I've got a function that simulates a stochastic system of chemical reactions. I now want to use the Process class from Pythons Multiprocessing library to run the stochastic simulation function several times.

I tried the following:

v = range(1, 51)
def parallelfunc(v):     
    gillespie_tau_leaping(start_state, LHS, stoch_rate, state_change_array)


if __name__ == '__main__':
    start = datetime.utcnow()
    p = Process(target=parallelfunc, args=(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50))
    p.start()    
    p.join()
    end = datetime.utcnow()
    sim_time = end - start
    print(f"Simualtion utc time:\n{sim_time}")

but this results in the error TypeError: parallelfunc() takes 1 positional argument but 50 were given

Then i tried just passing range(1, 51) to both parallelfunc and the args parameter of process but then I just get SyntaxError: invalid syntax on the deceleration of parallelfunc

The method of using a function like parallelfunc in this way works when using pool.map there I just pass parallelfunc followed by a list from 1 - 50.

But I can't figure out whats going wrong here.

Any suggestions Cheers.

Upvotes: 0

Views: 32

Answers (2)

Francisco Parrilla
Francisco Parrilla

Reputation: 513

I think the error is because your are giving 50 parameters as arguments for the parallelfunc, which you defined it to be only one argument. Maybe try adding list() so it is only one argument, which contains the 50 numbers. However, I dont know if the number of numbers is high.

Upvotes: 0

Redfer
Redfer

Reputation: 162

thats cause you have given too many arguments. try

def parallelfunc(*v):     
     gillespie_tau_leaping(start_state, LHS, stoch_rate, state_change_array)

this allows you to take multiple arguments

Upvotes: 1

Related Questions