0

3 Consumers 2 producers. Reading and writing to one buffer. Producer A is pushing 1 element to buffer (length N) and Producer B is pushing 2 elements to buffer. No active waiting. I can't use System V semaphores.

Sample code for producer A:

void producerA(){
  while(1){
    sem_wait(full);
    sem_wait(mutex);

    Data * newData = (Data*) malloc(sizeof(Data));
    newData->val = generateRandomletter();
    newData->A = false;
    newData->B = false;
    newData->C = false;

    *((Data*) mem+tail) = *newData;

    ++elements;
    tail = (tail + 1) % N;

    sem_post(mutex); 
    sem_post(empty);
  }
}

Consumers look similar except they read or consume but that's irrelevant. I am having a lot of trouble with Producer B. Obviously I can't do things like

sem_wait(full); sem_wait(full);

I also tried having a different semaphore for producer B that would be upped the first time there are 2 or more free spots in the buffer. But that didn't work out because I still need to properly lower and increase semaphores full and empty.

In what ways can I solve this problem?

Michael Albers
  • 3,721
  • 3
  • 21
  • 32
Aaroneiros
  • 111
  • 7

1 Answers1

1

https://gist.github.com/RobPiwowarek/65cb9896c109699c70217ba014b9ed20 That would be solution to the entire problem I had.

TLDR: The easiest synchronisation I can provide was with using semaphores full and empty to represent the number of elements I have pushed to buffer. However that kind of solution does not work for POSIX semaphores if I have a producer that creates 2 elements.

My solution is a different concept.
The outline of a process comes down to:

while(1){  
    down(mutex);
    size = get size
    if (condition related to size based on what process this is)
    {
         do your job;
         updateSize(int diff); // this can up() specific semaphores 
                               // based on size
                               // each process has his own semaphore
         up(mutex);
    }
    else 
    {
         up(mutex);
         down(process's own semaphore);
         continue;
    }
}

I hope this will be useful to someone in the future.

Aaroneiros
  • 111
  • 7