POSIX semaphores

  1. Posix semaphores are easy to use
  2. Exercises   1   2


All POSIX semaphore functions and types are prototyped or defined in semaphore.h. To define a semaphore object, use

      sem_t sem_name;

To initialize a semaphore, use sem_init():

      int sem_init(sem_t *sem, int pshared, unsigned int value);

Example of use:
      sem_init(&sem_name, 0, 10);

To wait on a semaphore, use sem_wait:
      int sem_wait(sem_t *sem);
Example of use:
      sem_wait(&sem_name); 


To increment the value of a semaphore, use sem_post:
      int sem_post(sem_t *sem);
Example of use:
      sem_post(&sem_name); 


To find out the value of a semaphore, use
      int sem_getvalue(sem_t *sem, int *valp);

Example of use:
      int value; 
      sem_getvalue(&sem_name, &value); 
      printf("The value of the semaphors is %d\n", value);

To destroy a semaphore, use
      int sem_destroy(sem_t *sem);
Example of use:
     sem_destroy(&sem_name); 


Exercise 1. Create a directory called posixthreads in your csc1600 directory and download this simple PC_posix.c file in your posixthreads directory. The file contains the code for a producer thread that attempts to write 10 characters in a buffer of size 4.

Extend this code to implement a solution to the producer consumer problem discussed in class using Posix threads and semaphores. Assume that there is only one producer and one consumer. The output of your code should be similar to the following:

      Producing A ...
      Producing B ...
      Producing C ...
      Producing D ...
      Consuming A ...
      Consuming B ...
      Consuming C ...
      Consuming D ...
      Producing E ...
      Producing F ...
      Producing G ...
      Producing H ...
      Consuming E ...
      Consuming F ...
      Consuming G ...
      Consuming H ...
      Producing I ...
      Producing J ...
      Consuming I ...
      Consuming J ...

Exercise 2. Modify the code from exercise 1 to work with multiple producers and multiple consumers. Create three producers and three consumers in the main function. Comment well your code. Compile and run your program and observe the output.

To compile a program that uses pthreads and posix semaphores, use

     gcc -o filename filename.c -lpthread -lrt