Worker Pools in Fortran

Our example demonstrates how to implement a worker pool using Fortran. While Fortran doesn’t have built-in concurrency primitives like goroutines and channels, we can simulate similar behavior using OpenMP for parallel processing.

program worker_pools
    use omp_lib
    implicit none

    integer, parameter :: NUM_JOBS = 5
    integer, parameter :: NUM_WORKERS = 3
    integer :: jobs(NUM_JOBS)
    integer :: results(NUM_JOBS)
    integer :: i

    ! Initialize jobs
    do i = 1, NUM_JOBS
        jobs(i) = i
    end do

    ! Start the worker pool
    !$omp parallel num_threads(NUM_WORKERS) shared(jobs, results)
    call worker()
    !$omp end parallel

    ! Print results
    do i = 1, NUM_JOBS
        print *, "Job", i, "result:", results(i)
    end do

contains

    subroutine worker()
        integer :: id, j
        
        id = omp_get_thread_num() + 1
        
        !$omp do
        do j = 1, NUM_JOBS
            print *, "worker", id, "started job", jobs(j)
            call sleep(1)  ! Simulate work
            print *, "worker", id, "finished job", jobs(j)
            results(j) = jobs(j) * 2
        end do
        !$omp end do
    end subroutine worker

end program worker_pools

In this Fortran implementation:

  1. We use OpenMP to create a pool of worker threads.

  2. The worker subroutine represents our worker function. It processes jobs in parallel using OpenMP’s work-sharing constructs.

  3. We use a sleep call to simulate an expensive task, similar to the original example.

  4. The main program initializes the jobs, starts the worker pool, and then prints the results.

  5. We use shared arrays jobs and results to communicate between the main program and the workers, instead of channels.

To compile and run this program, you’ll need a Fortran compiler with OpenMP support. For example, using gfortran:

$ gfortran -fopenmp worker_pools.f90 -o worker_pools
$ ./worker_pools
worker 1 started job 1
worker 2 started job 2
worker 3 started job 3
worker 1 finished job 1
worker 1 started job 4
worker 2 finished job 2
worker 2 started job 5
worker 3 finished job 3
worker 1 finished job 4
worker 2 finished job 5
Job 1 result: 2
Job 2 result: 4
Job 3 result: 6
Job 4 result: 8
Job 5 result: 10

This program demonstrates parallel processing in Fortran, simulating a worker pool. It processes 5 jobs using 3 worker threads, with each job taking about 1 second. The total execution time will be around 2 seconds, as the jobs are processed concurrently.

Note that the exact output order may vary between runs due to the nature of parallel execution.