The waiting on other threads is accomplished by using the function pthread_join() (more later).
Thread A invokes:
pthread_join( Tid, &status );
Tid = ID of a thread
status = variable to receive the exit state of thread.
(&status will pass the variable by reference)
|
The thread Tid completes if:
|
Example: waiting for 1 thread (Hello World)
#include <pthread.h>
/* ==================================
Thread prints "Hello World"
================================== */
void *worker(void *arg)
{
cout << "Hello World !" << endl;
return(NULL); /* Thread exits (dies) */
}
/* =================================================
MAIN: create a trhead and wait for it to finish
================================================= */
int main(int argc, char *argv[])
{
pthread_t tid;
/* ---------------------
Create threads
--------------------- */
if ( pthread_create(&tid, NULL, worker, NULL) )
{
cout << "Cannot create thread" << endl;
exit(1);
}
cout << "Main now waits for thread tid to finish...." << endl ;
pthread_join(tid, NULL);
exit(0);
}
|
How to run the program:
|
Better demo program:
Compile: gcc -o Join -pthread Join.c
Run: Join
|
int main(int argc, char *argv[])
{
int i, num_threads;
thread_t tid[100]; /* Thread ID used for thread_join() */
int param[100]; /* Parameters for threads */
num_threads = ... (number of threads to create);
/* --------------------------
Create threads
--------------------------- */
for (i = 0; i < num_threads; i = i + 1)
{
param[i] = ... ; // Initialize parameter for thread i
if ( pthread_create(&tid[i], &attr, worker, & param[i]) != 0 )
{
printf("Cannot create thread\n");
exit(1);
}
}
/* ----------------------------------
Wait for ALL threads to finish
---------------------------------- */
for (i = 0; i < num_threads; i = i + 1)
pthread_join(tid[i], NULL);
}
|
Previous example: thread01.C
How to run the program:
|