#include "headers.h" #include /* error checking left out for legibility */ /* size of thread bevy */ #define TH_NO 10 /* stuff to pass into thread */ typedef struct thread_arg { int id; float cost; } arg_t; /* stuff thread returns */ typedef struct thread_val { int id; float cost; } val_t; /* thing thread does */ void *entry_point(void *ptr); /* some verbosity */ void announce(void); int main(int argc, char *argv[]){ int i; pthread_t *thread_ids = (pthread_t *)calloc(TH_NO, sizeof(pthread_t)); arg_t *thread_args = (arg_t *)calloc(TH_NO, sizeof(arg_t)); val_t **thread_vals = (val_t **)calloc(TH_NO, sizeof(val_t*)); assert(thread_ids != NULL); assert(thread_args != NULL); assert(thread_vals != NULL); announce(); for(i = 0; i < TH_NO; i++){ thread_args[i].id = i; thread_args[i].cost = 3.14; } for(i = 0; i < TH_NO; i++){ if(pthread_create(&thread_ids[i], NULL, entry_point, &thread_args[i]) != 0){ fprintf(stderr, "Thread creation failed at i = %d\n", i); exit(EXIT_FAILURE); } } for(i = 0; i < TH_NO; i++){ if(pthread_join(thread_ids[i], (void **)&thread_vals[i]) != 0){ fprintf(stderr, "Thread joining failed at i = %d\n", i); exit(EXIT_FAILURE); } } for(i = 0; i < TH_NO; i++) fprintf(stderr, "Thread %d produced: %d %f\n", i, thread_vals[i]->id, thread_vals[i]->cost); exit(EXIT_SUCCESS); } void *entry_point(void *arg){ arg_t input; val_t *output; announce(); input = *((arg_t *)arg); output = (val_t *)malloc(sizeof(val_t)); assert(output != NULL); output->id = input.id; output->cost = input.cost * input.id; pthread_exit(output); } void announce(void){ fprintf(stderr, "Thread %lu of Process %ld with Parent %ld\n", (unsigned long int)pthread_self(), (long)getpid(), (long)getppid()); }