fortranopenmpgfortrancygwin-64

OpenMP's OMP_SET_NUM_THREADS() not working as expected


My knowledge about OpenMP is nothing but superficial. Yet I decided to recap old concepts I've learned in the past and to do so I downloaded some material with theory and examples. One of the 1st of those (Fortran-95) examples is:

    Program TestOMP1

        Use OMP_LIB

        !$OMP PARALLEL
        Write(*,*) "Hi from thread: ", OMP_GET_THREAD_NUM()
        !$OMP END PARALLEL

    End Program TestOMP1

I think this is the simplest program possible. It works as expected, producing the following output corresponding to my machine's eight threads:

 Hi from thread:            2
 Hi from thread:            4
 Hi from thread:            0
 Hi from thread:            6
 Hi from thread:            3
 Hi from thread:            1
 Hi from thread:            7
 Hi from thread:            5

But when I try to set a smaller number of threads, say four (4), with !$Call OMP_SET_NUM_THREADS() as I've done in the past.:

                ...
        Use OMP_LIB

        !$Call OMP_SET_NUM_THREADS(4)

        !$OMP PARALLEL
                 ...

I still get the same eight original threads. What's going on?

I've seen solutions and suggestions to this problem here in SO and elsewhere, stuff like export or set the number of threads as a terminal command, but none worked. If the command exists but is ineffective or useless, why does it exist in first place? Yet, I remember that it used to work in the past. What can I do? Would this be a Cygwin64 -specific problem?

Cygwin64 running on Windows 11, GNU Fortran (GCC) 12.4.0.


Solution

  • In !$Call OMP_SET_NUM_THREADS(4) you are missing a white space between the !$ sentinel for conditional compilation and the Fortran statement Call OMP_SET_NUM_THREADS(4), therefore the whole line in recognized as a comment by the compiler.

    You should insert a white space after !$:

    !$ Call OMP_SET_NUM_THREADS(4)
    

    The OpenMP specification says:

    The following conditional compilation sentinel is recognized in free form source files: !$

    To enable conditional compilation, a line with a conditional compilation sentinel must satisfy the following criteria:

    • The sentinel can appear in any column but must be preceded only by white space;
    • The sentinel must appear as a single word with no intervening white space;
    • Initial lines must have a space after the sentinel;
    • Continued lines must have an ampersand as the last non-blank character on the line, prior to any comment appearing on the conditionally compiled line.