Multi-threaded programming was introduced on the AS/400-iSeries back in V4R2, but was limited to C and Java programs. Multithreaded programming took a big step up with the release of V4R4 when multithreaded support was added to the RPG and COBOL languages. In an earlier tip, Introduction to multi-threaded programming -- part 1, we discussed the basics of multithreaded programming and how it is advantageous to both you and your users....
Now, let's take a look at how you actually go about creating a multi-threading program.
The mechanics of multithreaded programming
When a job starts on the System i/iSeries, the system creates a primary thread for that job. All programs and procedures are run in that primary thread unless you explicitly spawn off additional threads.
In procedure-based languages such as C and RPG, you use the appropriate API to spawn off secondary threads (e.g., the pthread_create API). One of the parameters that you send the API is a pointer to a procedure that will get control once the secondary thread has been established. This is called the start routine and must conform to a standard interface. This procedure will then dictate the course that the thread will take.
Code running in the secondary thread executes independently of all other threads although some data areas, such as global data, are shared. You end a thread by either calling an appropriate API (e.g., pthread_exit) or simply returning from its start routine; however, it does not automatically "return" to the thread that created it, which is off running its own code -- like a called procedure does.
Consider this example. Thread A spawns (i.e., creates) thread B. Thread A and thread B are now executing simultaneously. When thread B ends it is left in a sort of "limbo" state until its resources are freed up by thread A calling the pthread_detachAPI. Before calling the pthread_detach API however, thread A can call the pthread_join API to retrieve thread B's return value (called the status). If thread B is still running, the pthread_join API will wait for thread B to end and then retrieve its return value.
The lingo of multi-threaded programming
Here is a quick glossary of the basic terms of multithreaded programming.
About the author: Ron Turull is editor of Inside Version 5. He has more than 20 years' experience programming for and managing AS/400-iSeries systems.