Skip to main content

Problem:

Within the general subject of multi-threaded COBOL programming, the distinction between "local-storage" and "thread-local storage" may not be clear.  This Knowledgebase article illustrates the difference, with an explanation and example source code.

Resolution:

In the documentation for both Server Express and Net Express, there is a book named "Multi-threaded programming", where this subject is generally covered.

The documentation says thread-local storage is "persistent across calls".

This means you can call a single individual COBOL program repeatedly within the same thread, and it will "maintain state" across calls, that is, it will remember the values in its thread-local storage from the last time it was called in that thread.

Local-storage is different, because local-storage is initialized each time a program is entered (that is, values from previous calls are not remembered).

The attached file "ltdiff.tar" contains a demonstration main C program and one COBOL program (and a script named "compile.sh").  The C program calls pthread_create() to start two threads.  Each thread calls the COBOL program twice, so the COBOL program gets called ("reentered") 4 times total.

The results show that the COBOL program recognizes that it is within unique threads started by pthread_create() from C.  The results show that thread-local data is remembered across calls to the same module in the same thread, whereas local-storage is initialized at each entry, as intended.

Note that the example "test_cbl.c" calls cobinit() and cobtidy() as required when a C main calls COBOL, and it calls cobthreadtidy() as required when using "Threads in Other Languages", according to the documentation.

This example uses a C main and the POSIX Threads function pthread_create() to create threads, and so is designed for UNIX and Linux (or for Windows systems on which a POSIX Threads library has been installed).

As an alternative, the example could have used a COBOL main module and CBL_THREAD_CREATE to create threads.  This is an equally valid approach.  Micro Focus provides a full set of portable Multi-threading Library Routines for writing multi-threaded applications in COBOL.  In all such cases, thread-local-storage and local-storage behave the same way.

Attachments:

ltdiff.tar

Old KB# 2288