0

i am try to understand this code of producer&consumer using threads,since i am new in multi-threading programming:

#include <sys/time.h>
#include <stdio.h>
#include <pthread.h>
#include <errno.h>
#define SIZE 10
pthread_mutex_t region_mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t space_available = PTHREAD_COND_INITIALIZER;
pthread_cond_t data_available = PTHREAD_COND_INITIALIZER;
int b[SIZE]; /* buffer */
int size = 0; /* number of full elements */
int front,rear=0; /* queue */


void *producer()
{
int i = 0;
while (1) {
pthread_mutex_lock(&region_mutex);
while (size == SIZE) {

pthread_cond_broadcast(&data_available);
pthread_cond_wait(&space_available,&region_mutex);
}
if(i>99) i=-1;
add_buffer(i);
pthread_cond_broadcast(&data_available);
pthread_mutex_unlock(&region_mutex);
if (i==-1) break;
i = i + 1;
}
pthread_exit(NULL);
}


void *consumer()
{
int i,v;
While(1){
pthread_mutex_lock(&region_mutex);
while (size == 0) {
pthread_cond_broadcast(&space_available);
pthread_cond_wait(&data_available,&region_mutex);
}
v = get_buffer();
pthread_cond_broadcast(&space_available);
pthread_mutex_unlock(&region_mutex);
if (v==-1) break;
printf("got %d ",v);
}
pthread_exit(NULL);
}

what the meaning of this code and why we use it,and what the meaning of number 99:

if(i>99) i=-1;
add_buffer(i);
pthread_cond_broadcast(&data_available);
pthread_mutex_unlock(&region_mutex);
if (i==-1) break;
i = i + 1; 

thanks in advance for any help.

  • learn to use your systems debugger. Stepping thru that and watching the value of `i` should give you an understanding of what is happening. Good luck. – shellter Apr 04 '14 at 16:03
  • i am understand this code how it work except my question> – user3484846 Apr 04 '14 at 16:04
  • I can't say for certain, but `99` seems like an arbitrary value, and it s to keep from getting to the point that `i=99999999999`. I would *guess* that it is limiting the number of threads created. Good luck. – shellter Apr 04 '14 at 16:08
  • Not code ever changes the value of `size`. Also, your question is completely unfocused. You need to narrow down what specifically it is that you need explained. Stating things that you *do* understand would help a lot, so we know where to start from. (Or what to correct if you got it wrong.) – David Schwartz Apr 04 '14 at 19:12

0 Answers0