F2PY modules in parallel

Viewed 245

I have an existing Fortran module that I want to run in parallel. For example, I want 8 instances of the module, each with its own variable scope, all working at once. Is that possible with f2py? From the documentation, it seems that when you import a module, you only have access to a single copy of the Fortran object.

I'm newish to Python and very new to Fortran, so let me know if this approach is even worth investigating.

1 Answers

Yes you can run your imported functions from the f2py-object like any other function in parallel, for example using concurrent.futures. For example, it can look like this on the python side:

import concurrent.futures as cf
import f2py_module as fm
# Or if a fortran module "my_module" is wrapped, do
from f2py_module import my_module as fm

print (fm.__doc__) # to see functions definitions, comment out

def task(arg):
    """This wrapper is not needed, but usually convenient to define
    redundant arguments or transforming the result somehow"""
    res = fm.calculate(arg) # calculate is a Fortran subroutine
    return res 

PEX = cf.ProcessPoolExecutor(4) # 4 threads here

args = [1,2,3,4,5] 

processes = [PEX.submit(task,arg) for arg in args]
res = [pr.result() for pr in processes]

for re in res:
    print(re)
Related