Mutexes in COBOL
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 COBOL program, we define a container structure (WS-CONTAINER
) that holds two counters. Since we want to update it concurrently from multiple threads, we add a mutex (WS-MUTEX
) to synchronize access.
The INCREMENT-A
and INCREMENT-B
procedures lock the mutex before accessing the counters and unlock it afterward. This ensures that only one thread can modify the counters at a time.
In the START-THREADS
procedure, we create three threads: two that increment counter A and one that increments counter B. We use the CBL_CREATE_THREAD
call to start the threads and CBL_WAIT_ON_MULTIPLE_THREADS
to wait for them to finish.
Note that the zero value of a mutex is usable as-is in COBOL, so no initialization is required.
Running the program shows that the counters are updated as expected:
This example demonstrates how to use mutexes to safely manage shared state across multiple threads in COBOL. While COBOL doesn’t have built-in goroutines like Go, we can achieve similar concurrency using threads and synchronization primitives.
Next, we’ll look at implementing this same state management task using only threads and message passing.