Mutexes in Fortran
In the previous example, we saw how to manage simple counter state using atomic operations. For more complex state, we can use a mutex to safely access data across multiple threads.
In this Fortran implementation:
We define a
container
type that holds a mutex (implemented as an integer for use with OpenMP) and an array of counters.The
inc
subroutine increments a specific counter, using OpenMP’s lock routines to ensure thread safety.The
do_increment
subroutine callsinc
in a loop, similar to the original example.In the main program, we initialize the container, create parallel sections to run the increment operations concurrently, and then print the results.
We use OpenMP for parallelism, which is a common approach in Fortran for shared-memory parallelism.
Instead of a map, we use a simple integer array for counters. The index of the array represents the “name” of the counter.
To compile and run this program, you would typically use a command like:
This output shows that the counters were updated as expected, with the first counter (index 1) incremented to 20000 and the second counter (index 2) to 10000.
Note that Fortran doesn’t have built-in support for maps or hash tables, so we’ve simplified the example to use array indices instead of string keys. Also, Fortran doesn’t have a direct equivalent to goroutines, so we’ve used OpenMP parallel sections to achieve similar concurrency.
In the next example, we’ll look at implementing this same state management task using only threading and message passing.