Stateful Goroutines in COBOL
IDENTIFICATION DIVISION.
PROGRAM-ID. STATEFUL-ROUTINES.
ENVIRONMENT DIVISION.
DATA DIVISION.
WORKING-STORAGE SECTION.
01 WS-STATE.
05 WS-MAP OCCURS 5 TIMES.
10 WS-KEY PIC 9(5).
10 WS-VALUE PIC 9(5).
01 WS-READ-OPS PIC 9(10) COMP.
01 WS-WRITE-OPS PIC 9(10) COMP.
01 WS-RANDOM PIC 9(5).
PROCEDURE DIVISION.
MAIN-PROCEDURE.
PERFORM INITIALIZE-STATE
PERFORM START-ROUTINES
PERFORM DISPLAY-RESULTS
STOP RUN.
INITIALIZE-STATE.
MOVE 0 TO WS-READ-OPS
MOVE 0 TO WS-WRITE-OPS.
START-ROUTINES.
PERFORM VARYING WS-I FROM 1 BY 1 UNTIL WS-I > 100
PERFORM READ-ROUTINE
END-PERFORM
PERFORM VARYING WS-J FROM 1 BY 1 UNTIL WS-J > 10
PERFORM WRITE-ROUTINE
END-PERFORM.
READ-ROUTINE.
PERFORM GENERATE-RANDOM
COMPUTE WS-KEY = FUNCTION MOD (WS-RANDOM, 5) + 1
ADD 1 TO WS-READ-OPS.
WRITE-ROUTINE.
PERFORM GENERATE-RANDOM
COMPUTE WS-KEY = FUNCTION MOD (WS-RANDOM, 5) + 1
PERFORM GENERATE-RANDOM
MOVE WS-RANDOM TO WS-VALUE (WS-KEY)
ADD 1 TO WS-WRITE-OPS.
GENERATE-RANDOM.
COMPUTE WS-RANDOM = FUNCTION RANDOM * 100000.
DISPLAY-RESULTS.
DISPLAY "readOps: " WS-READ-OPS
DISPLAY "writeOps: " WS-WRITE-OPS.
In this COBOL example, we’ve translated the concept of stateful goroutines to a more procedural approach, which is more suitable for COBOL’s paradigm. Here’s an explanation of the key parts:
We define a state structure
WS-STATE
with a map-like arrayWS-MAP
that can hold 5 key-value pairs.We use
WS-READ-OPS
andWS-WRITE-OPS
to keep track of the number of read and write operations.The
MAIN-PROCEDURE
initializes the state, starts the routines, and displays the results.START-ROUTINES
simulates the concurrent operations by performing 100 read operations and 10 write operations.READ-ROUTINE
andWRITE-ROUTINE
simulate the read and write operations on the state. They use a random number generator to select keys and values.GENERATE-RANDOM
creates a random number, simulating the functionality ofrand.Intn()
in the original Go code.Finally,
DISPLAY-RESULTS
shows the number of read and write operations performed.
This COBOL program doesn’t have true concurrency like the Go version with goroutines. Instead, it sequentially performs the read and write operations. The concept of channels for communication between goroutines is replaced by direct updates to the shared state and operation counters.
To run this COBOL program, you would typically compile it and then execute the resulting binary. The exact commands may vary depending on your COBOL compiler and environment.
$ cobc -x stateful-routines.cob
$ ./stateful-routines
readOps: 0000000100
writeOps: 0000000010
Note that the actual numbers of read and write operations will be fixed in this COBOL version, unlike the Go version where they could vary due to the concurrent nature of goroutines.