Search code examples
c++operating-systemsynchronizationsemaphoreproducer-consumer

confusion with semaphore definitions


For semaphore implementations, what does process specify? In the context of the producer/consumer problem, is the process the producer method/Consumer method? Or is it P() if we are in P() and the value is less than 0?

      P() {
                value = value –1;
                If value < 0
                add the calling process to this semaphore’s list;
                block this process
          }

EXAMPLE If Consumer runs first before Producer produces its first item

Consumer would decrement the full value -> full = -1 and then since the value is less than 1, it would add the calling process to this semaphore’s list. But I’m not sure what process is. And what does it mean to block this process? Does it mean that the entire method for consumer is at halt, and producer method runs?

code:

#define N 100
typedef int semaphore;
Semaphore fullBuffer = 0; // Initially, no item in buffer
Semaphore empty = N; // Initially, num empty buffer
Semaphore mutex = 1;      // No thread updating the buffer

void producer(void) {
  int item;
  while(TRUE){
      item = produce_item();
      down(&empty);
      down(&mutex);
      insert_item(item);
      up(&mutex);
      up(&full);
      }
    }

void consumer(void) {
 int item;
 while(TRUE){
      down(&full);
      down(&mutex);
      item = remove_item();
      up(&mutex);
      up(&empty);
      consume_item(item);
      }
}

Solution

  • A process, in this usage, is exactly like a thread. Usually when 'multiprocess' is used instead of 'multithreaded', it implies that the kernal handles the threading, which allows the computer to take advantage of multiple cores. However, that isn't important for this specific implementation, and is also false for this specific implementation, because nothing is atomic.

    Blocking the process here means that a process that calls P and decrememnts the value to anything negative will halt its own execution when it reaches the 'block this process' command.

    Assuming multi threading, your 'producer' command will continually decrease the empty semaphore unless it tries to decrement it below zero, in which case it will be halted, and only the 'consumer' command will run. At least, only 'consumer' will run until it increases the empty semaphore enough that 'producer' can now run. You can also switch both 'empty'<->'full' and 'producer'<->'consumer' in the previous two sentences, and they should remain correct.

    Also, I suggest you read up on semaphores elsewhere, because they are a basic part of threading/multiprocessing, and other people have described them better than I ever could. (Look at the producer/consumer example there.)