In many cases, a thread has to wait until some other threads terminate. This is the job of function thr_join(). The syntax of thr_join() is:
int thr_join(
thread_t wait_for, /* thread we are waiting */
0, /* 0 is fine with use */
void **status); /* status in thr_create() */
A call to thr_join() indicates that the caller wants to wait until
the completion of some thread.
#include <thread.h>
void Task(void *Junk)
{
.......
thr_exit(NULL);
}
void main(void)
{
thread_t TaskID;
size_t TaskStatus;
thr_create(NULL,0,Task,(void *) NULL,0,&TaskID);
......
thr_join(TaskID, 0, (void *) &TaskStatus);
}
If thr_join() in the main program is reached before
Task() terminates, the main program waits there until
Task() completes. Then, the execution of main resumes.
This is illustrated by the following diagram:
On the other hand, if Task() has already terminated when the main program reaches thr_join(), there is nothing to ``join'' and the main program proceeds:
#include#include #define MAX_ITERATION 200 void *ThreadA(void *DontNeedIt) { int i; for (i = 1; i <= MAX_ITERATION; i++) printf("Thread A speaking: iteration %d\n", i); thr_exit(NULL); } void *ThreadB(void *DontNeedIt) { int i; for (i = 1; i <= MAX_ITERATION; i++) printf(" Thread B speaking: iteration %d\n", i); thr_exit(NULL); } void main(void) { thread_t FirstThread, SecondThread; size_t StatusFromA, StatusFromB; thr_create(NULL, 0, ThreadA, (void *) NULL, 0, &FirstThread); thr_create(NULL, 0, ThreadB, (void *) NULL, 0, &SecondThread); thr_join(FirstThread, 0, (void *) &StatusFromA); thr_join(SecondThread, 0, (void *) &StatusFromB); }