| 1 | /*****************************************************************************
|
|---|
| 2 | * FILE: join.c
|
|---|
| 3 | * DESCRIPTION:
|
|---|
| 4 | * This example demonstrates how to "wait" for thread completions by using
|
|---|
| 5 | * the Pthread join routine. Threads are explicitly created in a joinable
|
|---|
| 6 | * state for portability reasons. Use of the pthread_exit status argument is
|
|---|
| 7 | * also shown. Compare to detached.c
|
|---|
| 8 | * AUTHOR: 8/98 Blaise Barney
|
|---|
| 9 | * LAST REVISED: 01/30/09
|
|---|
| 10 | ******************************************************************************/
|
|---|
| 11 | #include "pthread.cvh"
|
|---|
| 12 | #include <civlc.h>
|
|---|
| 13 | #include <stdio.h>
|
|---|
| 14 | #include <stdlib.h>
|
|---|
| 15 | #define NUM_THREADS 4
|
|---|
| 16 |
|
|---|
| 17 | void *BusyWork(void *t)
|
|---|
| 18 | {
|
|---|
| 19 | int i;
|
|---|
| 20 | long tid;
|
|---|
| 21 | double result=0.0;
|
|---|
| 22 | tid = (long)t;
|
|---|
| 23 | printf("Thread %ld starting...\n",tid);
|
|---|
| 24 | for (i=0; i<1000000; i++)
|
|---|
| 25 | {
|
|---|
| 26 | result = result + sin(i) * tan(i);
|
|---|
| 27 | }
|
|---|
| 28 | printf("Thread %ld done. Result = %e\n",tid, result);
|
|---|
| 29 | pthread_exit((void*) t);
|
|---|
| 30 | }
|
|---|
| 31 |
|
|---|
| 32 | int main (int argc, char *argv[])
|
|---|
| 33 | {
|
|---|
| 34 | pthread_t thread[NUM_THREADS];
|
|---|
| 35 | pthread_attr_t attr;
|
|---|
| 36 | int rc;
|
|---|
| 37 | long t;
|
|---|
| 38 | void *status;
|
|---|
| 39 |
|
|---|
| 40 | /* Initialize and set thread detached attribute */
|
|---|
| 41 | pthread_attr_init(&attr);
|
|---|
| 42 | pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
|
|---|
| 43 |
|
|---|
| 44 | for(t=0; t<NUM_THREADS; t++) {
|
|---|
| 45 | printf("Main: creating thread %ld\n", t);
|
|---|
| 46 | rc = pthread_create(&thread[t], &attr, BusyWork, (void *)t);
|
|---|
| 47 | if (rc) {
|
|---|
| 48 | printf("ERROR; return code from pthread_create() is %d\n", rc);
|
|---|
| 49 | exit(-1);
|
|---|
| 50 | }
|
|---|
| 51 | }
|
|---|
| 52 |
|
|---|
| 53 | /* Free attribute and wait for the other threads */
|
|---|
| 54 | pthread_attr_destroy(&attr);
|
|---|
| 55 | for(t=0; t<NUM_THREADS; t++) {
|
|---|
| 56 | rc = pthread_join(thread[t], &status);
|
|---|
| 57 | if (rc) {
|
|---|
| 58 | printf("ERROR; return code from pthread_join() is %d\n", rc);
|
|---|
| 59 | exit(-1);
|
|---|
| 60 | }
|
|---|
| 61 | printf("Main: completed join with thread %ld having a status of %ld\n",t,(long)status);
|
|---|
| 62 | }
|
|---|
| 63 |
|
|---|
| 64 | printf("Main: program completed. Exiting.\n");
|
|---|
| 65 | pthread_exit(NULL);
|
|---|
| 66 | }
|
|---|
| 67 |
|
|---|
| 68 |
|
|---|