/*Example:*/ #include #include #include struct phonebookentry { char name[64]; long int phonenumber; char flags[16]; }; struct arguments { struct phonebookentry *apbe; long int phonenumber; }; pthread_mutex_t lock; pthread_cond_t cond; int data_available=0; int done=0; void *fetch(void *); #define NUM_PHONEBOOK_ENTRIES 4 #define NUM_THREADS 10 #define LOOKUPS_TO_DO 10 struct phonebookentry phonebook[NUM_PHONEBOOK_ENTRIES]={{"alex",9999999,"home"},{"david",2222222,"mobile"},{"matthew",3333333,"work"},{"sarah",1234567,"mobile"}}; int main (void) { struct arguments *arg; struct phonebookentry *results; pthread_t thread_id[NUM_THREADS]; long int i,lookup_numbers[LOOKUPS_TO_DO]={9999999,2222222,3333333,4444444,9999999,2222222,3333333,4444444,1234567,7654321}; /*initialize*/ pthread_mutex_init(&lock,NULL); pthread_cond_init(&cond,NULL); arg=calloc(1,sizeof(struct arguments)); results=calloc(LOOKUPS_TO_DO,sizeof(struct phonebookentry)); /*here we strart two worker threads */ for(i=0;iphonenumber=lookup_numbers[i]; arg->apbe=&(results[i]); data_available=1; pthread_cond_signal(&cond); pthread_mutex_unlock(&lock); /*wait until thread receives the data*/ while(data_available==1) { /*do nothing*/ } } /* wait for all threads to finish */ printf("Waiting for all lookups to finish\n"); while(donephonenumber; npbe=((struct arguments *)arg)->apbe; data_available=0; pthread_mutex_unlock(&lock); /* fetch value from a database */ printf("Thread %d: Fetch started, looking for %d\n",(int)pthread_self(),number); i=0; while(i<1000*number) /*simulate long database lookup*/ i=i+1; for(i=0;iname,npbe->phonenumber); else printf("Thread %d: %d Number not found\n",number, (int)pthread_self()); done++; } }