0

My current code answers the producer consumer question, but I want to implement it in a different way. I do not want to use a global variable to keep track of the count in my buffer stack . What should my thought process be?

typedef int semaphore;
semaphore mutex, full, empty;

int count = 0;

    union semun {
        int val;
        struct semid_ds *buf;
        unsigned short      *array; 
    } arg;


int buffer[N];

These are the functions that use count

int remove_item()
{
    int ret = buffer[--count];
    buffer[count] = 0;
    return ret;
}

void insert_item(int item)
{
    buffer[count++] = item;
}

int produce_item(){
    int item = rand()%50 +1;
    printf("Producer produces %d\n",item);
    sleep(1);
    return item;
}

And my producer consumer functions

void* consumer(void * arg) {
    int item = 0;
    while(1){
        down(full);
        down(mutex);    
        item = remove_item();
        buffer[count++] = item; 
        up(mutex);
        up(empty);
        consume_item(item);
    }
    return 0;
}

void* producer(void* arg) { 
    int item, i =0;
    while(1){
        item  = produce_item();
        down(empty);
        down(mutex);
        insert_item(item);
        up(mutex);
        up(full);
        sleep(1);

    }
Damenace
  • 1
  • 2
  • The count, the three semaphores and the buffer space all belong in one 'PCqueue' struct. You need a function to return an initialized one, (or pointer to it). The struct can then be easily raised on the stack of any thread. – ThingyWotsit May 11 '17 at 13:16
  • the posted code has not implemented ANY semaphores. The resulting `race` conditions will result in corrupted,lost,duplicated data. – user3629249 May 11 '17 at 20:58

1 Answers1

1

The usual way is to pass the variables used by the thread as a parameter. Most thread libraries (POSIX pthread, Windows CreateThread etc) support this by allowing a void pointer to any form of data to get passed to the thread upon creation - that's what the "arg" parameter in your thread callback functions is for.

Lundin
  • 195,001
  • 40
  • 254
  • 396