Example: Waiting for threads in a Pthread program
This example shows a Pthread program starting several threads, waiting for them to finish, and checking their status after they are completed.
Note: By using the code examples, you agree to the terms of the Code license and disclaimer information.
/*
Filename: ATEST13.QCSRC
The output of this example is as follows:
Enter Testcase - LIBRARY/ATEST15
Create/start some worker threads
Thread 00000000 000001a4: Entered
Thread 00000000 000001a4: Working
Wait for worker threads to complete, release their resources
Thread 00000000 000001a8: Entered
Thread 00000000 000001a8: Working
Thread 00000000 000001a5: Entered
Thread 00000000 000001a5: Working
Thread 00000000 000001a6: Entered
Thread 00000000 000001a6: Working
Thread 00000000 000001a7: Entered
Thread 00000000 000001a7: Working
Thread 00000000 000001a4: Done with work
Thread 00000000 000001a8: Done with work
Thread 00000000 000001a6: Done with work
Thread 00000000 000001a7: Done with work
Thread 00000000 000001a5: Done with work
Check all thread's results
Main completed
*/
#define _MULTI_THREADED
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#define THREADGROUPSIZE 5
#define checkResults(string, val) { \
if (val) { \
printf("Failed with %d at %s", val, string); \
exit(1); \
} \
}
void *theThread(void *parm)
{
printf("Thread %.8x %.8x: Entered\n", pthread_getthreadid_np());
printf("Thread %.8x %.8x: Working\n", pthread_getthreadid_np());
sleep(15);
printf("Thread %.8x %.8x: Done with work\n", pthread_getthreadid_np());
return NULL;
}
int main(int argc, char **argv)
{
pthread_t thread[THREADGROUPSIZE];
void *status[THREADGROUPSIZE];
int i;
int rc=0;
printf("Enter Testcase - %s\n", argv[0]);
printf("Create/start some worker threads\n");
for (i=0; i <THREADGROUPSIZE; ++i)
{
rc = pthread_create(&thread[i], NULL, theThread, NULL);
checkResults("pthread_create()\n", rc);
}
printf("Wait for worker threads to complete, release their resources\n");
for (i=0; i <THREADGROUPSIZE; ++i) {
rc = pthread_join(thread[i], &status[i]);
checkResults("pthread_join()\n", rc);
}
printf("Check all thread's results\n");
for (i=0; i <THREADGROUPSIZE; ++i) {
if (status[i] != NULL) {
printf("Unexpected thread status\n");
}
}
printf("Main completed\n");
return 0;
}