| 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 %d starting...\n",tid); // Removed l from %ld, unsupported
|
|---|
| 24 | for (i=0; i<1000000; i++)
|
|---|
| 25 | {
|
|---|
| 26 | result = result + sin(i) * tan(i);
|
|---|
| 27 | }
|
|---|
| 28 | printf("Thread %d done. Result = %e\n",tid, result); // Removed l from %ld, unsupported
|
|---|
| 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); //Added address as conversion from
|
|---|
| 47 | if (rc) { // int directly to void * is unsupported
|
|---|
| 48 | $assert(false, "ERROR; return code from pthread_create() is" + (char)rc);
|
|---|
| 49 | }
|
|---|
| 50 | }
|
|---|
| 51 |
|
|---|
| 52 | /* Free attribute and wait for the other threads */
|
|---|
| 53 | pthread_attr_destroy(&attr);
|
|---|
| 54 | for(t=0; t<NUM_THREADS; t++) {
|
|---|
| 55 | rc = pthread_join(thread[t], &status);
|
|---|
| 56 | if (rc) {
|
|---|
| 57 | $assert(false, "ERROR; return code from pthread_create() is" + (char)rc);
|
|---|
| 58 | }
|
|---|
| 59 | printf("Main: completed join with thread %ld having a status of %ld\n",t,(long)status);
|
|---|
| 60 | }
|
|---|
| 61 |
|
|---|
| 62 | printf("Main: program completed. Exiting.\n");
|
|---|
| 63 | pthread_exit(NULL);
|
|---|
| 64 | }
|
|---|
| 65 |
|
|---|
| 66 |
|
|---|