/∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗ ∗ FILE: join1.c

∗ DESCRIPTION:

∗ This example demonstrates how to ”wait” for thread completions by using

∗ the Pthread join routine. Since not all current implementations of

∗ Pthreads create threads in a joinable state, the threads in this

∗ example are explicitly created in a joinable state so that they can

∗ be joined later. ∗

∗ SOURCE: 8/98 Blaise Barney

∗ LAST REVISED: 10/8/99 Blaise Barney ∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗/

#include <pthread.h>
#include <stdio.h>

#define NUM THREADS 3

void ∗BusyWork(void ∗null) {

int i;

double result=0.0;

for (i=0; i<1000000; i++)

{

result = result + (double)random(); } printf("Thread result = %e\n",result); pthread exit((void ∗) 0);

}

int main(int argc, char ∗argv[]) {

pthread t thread[NUM THREADS];

pthread attr t attr;

int rc, t, status;

/∗ Initialize and set thread detached attribute ∗/

pthread attr init(&attr);

pthread attr setdetachstate(&attr, PTHREAD CREATE JOINABLE);

for(t=0;t<NUM THREADS;t++)

{

      printf("Creating thread %d\n", t);

rc = pthread create(&thread[t], &attr, BusyWork, NULL); if (rc) {

         printf("ERROR; return code from pthread create() is %d\n", rc);

exit(−1);

} }

/∗ Free attribute and wait for the other threads ∗/ pthread attr destroy(&attr); for(t=0;t<NUM THREADS;t++) {

rc = pthread join(thread[t], (void ∗∗)&status);

if (rc)

{

      printf("ERROR return code from pthread join() is %d\n", rc);

exit(−1); }

   printf("Completed join with thread %d status= %d\n",t, status);

}

pthread exit(NULL); }