Search code examples
c++multithreadingfortranfortran77fortran-common-block

Fortran 77 common blocks in multithreading C++ application


I develop one C++ program which calls a Fortran 77 routine. The main C++ program may run multithreaded. However, it happens that the Fortran 77 routine hides several common blocks which are modified on each call depending on its arguments.

I am afraid that all common blocks may be shared between multiple threads and that concurrent accesses to these blocks will probably mess everything.

  • First question : Am I right? Would common blocks be shared between multiple threads?

  • Second question : Is there a simple way to avoid it? Rewriting the Fortran routines seems unaffordable, I am rather looking for a way so that each thread has its own copy of all common blocks (which are not large, should be fast to copy). I do not know if a compiling option would help or if OpenMP could help me.


Solution

  • Yes, common blocks are shared.

    In OpenMP it is possible to specify a common block as THREADPRIVATE. Each thread than makes a new instance of the common block dynamically. To copy the data from the original one use the COPYIN specifier. See also Difference between OpenMP threadprivate and private

    The basic syntax is

    !$OMP THREADPRIVATE (/cb/, ...)  
    

    where cb is the name of a common block. See https://computing.llnl.gov/tutorials/openMP/#THREADPRIVATE