Intel® Fortran Compiler
Build applications that can scale for the future with optimized code designed for Intel® Xeon® and compatible processors.
28455 Discussions

Advice for C calling Fortran with multi thread issue

LTthink
Novice
728 Views

Hi there,

We have program in C calling FORTRAN (old routines compiled in lib), which works well.

We try to implement an optimizer in C, which will call same FORTRAN code repeatedly with multi thread. This caused lots of issues, such as severe 29 and 43 (the FORTRAN code is opening/reading files). As expected, the instances of the FORTRAN code is overwriting each others' in the shared memory.

And advice on how to resolve this?

Thank you!

0 Kudos
4 Replies
jimdempseyatthecove
Honored Contributor III
717 Views

Without seeing the code, it is difficult to answer.

One potential way, is to make all static data (aka COMMON, SAVE and MODULE) threadprivate

A second way is to pass in a user defined type with context.

A complicating factor is: How are you doing your multi-threading?

std::thread, OpenMP thread, other threading?

And, are your C++ threads persistent or do you spawn once for each call into the Fortran code?

Jim Dempsey

Steve_Lionel
Honored Contributor III
711 Views

You also need to add the RECURSIVE keyword before each SUBROUTINE or FUNCTION or else there will still be static data, some of which are created internally by the compiler. (In Fortran 2018 that would not be necessary, but I don't think ifort supports that change yet. The keyword is harmless otherwise.)

LTthink
Novice
699 Views

Thank you Dr. Steve!

We defined the Fortran subroutines with extern "C" in C codes, and pass data arrays in argument as pointers. Results from Fotran calculation is written back to the data arrays directly. I think this is causing the issues.

Do you mean I should add "RECURSIVE" before SUBROUTINE FunctionName in all Fortran code?

Thanks!

0 Kudos
LTthink
Novice
700 Views

Thank you Jim!

Data are stored in RECORD structure. How can I make it "threadprivate"? 

Multi-threading is done using Thread from the Boost C++ library. We defined the Fortran subroutines with extern "C", and pass data arrays in argument as pointers. Results from Fotran calculation is written back to the data arrays directly. I think this is causing the issues.

Thanks!

 

 

0 Kudos
Reply