POSIX semaphores
- Posix semaphores are easy to use
- 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);
- sem points to a semaphore object to initialize
- pshared is a flag indicating whether or not the semaphore should
be shared with fork()ed processes. LinuxThreads does not currently
support shared semaphores
- value is an initial value to set the semaphore to
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);
- sem_wait is an implementation of the DOWN operation discussed in class.
If the value of the semaphore is negative, the calling process blocks; one of the blocked
processes wakes up when another process calls sem_post.
To increment the value of a semaphore, use sem_post:
int sem_post(sem_t *sem);
Example of use:
sem_post(&sem_name);
- sem_post is an implementation of the UP operation discussed in class.
It increments the value of the semaphore and wakes up a blocked process waiting on the
semaphore, if any.
To find out the value of a semaphore, use
int sem_getvalue(sem_t *sem, int *valp);
- gets the current value of sem and places it in the location pointed to
by 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);
- destroys the semaphore; no threads should be waiting on the semaphore
if its destruction is to succeed.
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