Search code examples
multithreadingthread-safetyfortranparallel-processinglanguage-interoperability

Thread safe c# service using fortran dll


I have a c# windows service that starts a couple of threads and then each thread executes the same fortran function from a static dll library compiled with intel fortran 9.

When that happen, the first function keeps running just fine, while the other one triggers a c# exception.

Is there any compiler option to fix that? I googled a lot and only find recursive and save. I have to test them in the office tomorrow, but I am not optimistic.

PS: The fortran code has modules

Thanks!


Solution

  • Your problem is most likely the Fortran code. It's not uncommon for Fortran code to use shared global state variables, especially for older code. That's just one possibility, but there are plenty of other reasons why the Fortran code may not be thread-safe for your usage.

    If this is indeed the problem then you have a few options that may help:

    • Serialise calls to the Fortran code with a mutex/lock.
    • Re-factor the Fortran code to remove global shared state, e.g. moving it onto the stack.
    • Arrange that each thread uses a separate instance of the DLL.

    The last option is a rather gross hack, but it may be the most effective short term solution. To arrange that you have separate instances you just need to copy and rename the DLL so that each thread loads a DLL with a different name. Even if they are identical this is enough to persuade Windows to load separate instances of the DLL module and therefore separate instances of all global data.

    One final thought: make sure that you are linking the Fortran to the multi-threaded version of the Fortran runtime.