Skip to Content

How can you wait for several threads to finish?

Estimated Reading Time: 2 Minutes

When doing multithread programming, it is a best practice that a program should not finish its processing until all of its threads are finished as well.

In this article we provide a sample logic of how to check that all the threads started by a program are finished.

The first step is that when you call a thread, you add the thread handle of that call to a dynamic array similar to the following:

   call thread "progA"
        handle in W-Th
     *> using... would go here
    on overflow
       display "main: progA not found"
    not on overflow
        add 1 to max-progs
        move W-Th     to Prog-H-Thread(max-progs)
        move "progA"  to Prog-Name(max-progs)
   end-call
Do the same for any thread started by the main program.

Then, the paragraph to wait for all the threads to finish will have an infinite loop where it keeps sending status messages to the threads to check if they are still alive, when the status returned is "10", it means the thread is no longer running.
Something like the following:
WAIT-FOR-THREADS.
    perform until 1 = 2
        move 0 to ws-threads-running
        perform varying idx-prog from 1> by 1
                                 until idx-prog > max-progs
           if Prog-H-Thread(idx-prog) not = null
              wait for Prog-H-Thread(idx-prog) 
                   test only 
                   status in StatusWait
              if StatusWait = "10"     |*> The thread does not exist anymore, it's not running
                 move spaces  to Prog-Name(idx-prog)
                 move 0       to Prog-H-Thread(idx-prog)
              else
                 add 1 to ws-threads-running   |*> Thread's still running, count it as running
              end-if
           end-if
        end-perform

        if ws-threads-running = 0
          exit perform
        end-if
     end-perform.
Please download the Zip file with a full sample of this.

That sample shows a main program starting 3 threads. Each program being called in a thread performs a very simple arithmetic operations a few hundred times. Each program will delay few seconds to finish.
Each program will perform during a different length of time.

Using an isCOBOL Shell command prompt window, compile and run the test with the is_test.bat batch script.

When you run the test, you should get a console output like the following:
    > iscc *.cbl

    > iscrun MAIN
    main: Waiting for threads to finish ...
    progB: finished
    main: thread finished, program: progB
    progC: finished
    main: thread finished, program: progC
    progA: finished
    main: thread finished, program: progA
    main: All threads are done, program finished !
How can you wait for several threads to finish?