


Threads are created with either the PERFORM statement or the CALL statement. You simply add the word "THREAD" after the verb. The thread runs the target of the PERFORM or CALL statement. When the target completes, the thread is destroyed.
For example, to run the paragraph "OPEN-FILES" in a thread, you would code:
PERFORM THREAD OPEN-FILES
The main thread continues to execute at the statement following the PERFORM, while the OPEN-FILES code begins execution in a separate thread. When OPEN-FILES finishes, the thread is destroyed.
Threads are identified by thread handles. When you create a thread, you can optionally store its handle. Thread handles are used to communicate among threads. The next example demonstrates how this works.
There are times when you will want to ensure that a thread is complete before continuing in the program. For example, if one thread is used to open an application's files while another thread gets the user's password, you will not want to continue in the program until both tasks are complete, otherwise you might try to look up the password in a file that is closed. You can use the WAIT verb to make sure that both threads are complete before continuing. The WAIT verb causes the thread to wait for the specified thread to finish or send a message. The following example illustrates this process:
77 THREAD-1 USAGE HANDLE OF THREAD.
PERFORM THREAD OPEN-FILES, HANDLE IN THREAD-1
PERFORM GET-PASSWORD
WAIT FOR THREAD THREAD-1
PERFORM VALIDATE-PASSWORD
In this example, the paragraphs OPEN-FILES and GET-PASSWORD run in parallel. The WAIT statement ensures that OPEN-FILES is finished before the main thread goes on to validate the password.
LAST THREAD
The need to synchronize threads is so common that there is an optional phrase, LAST THREAD, that can be used to simplify coding. Note that the thread that LAST THREAD refers to is dynamic, so some care must be taken in its use. LAST THREAD refers to:
a. the last thread created by the current thread, or the last thread that the current thread communicated with, whichever was the last action
b. or, if neither of the actions described in (a) has occurred, the parent thread (the thread that created the current thread)
You can use the LAST THREAD phrase to eliminate the need to store a thread handle. For example, the preceding example could also be written as:
PERFORM THREAD OPEN-FILES
PERFORM GET-PASSWORD
WAIT FOR LAST THREAD
PERFORM VALIDATE-PASSWORD
A thread normally ends when the PERFORM or CALL statement that created it completes. You can end a thread earlier in the execution path with the STOP THREAD statement. Used by itself, STOP THREAD terminates the current thread. You can also specify a thread handle to stop another thread. If there is only one thread running, stopping that thread is equivalent to doing a STOP RUN.