Linux and macOS natively supports different types of semaphores. In order to
have a single (simple) semaphore API that works on both Linux and macOS you will
use a portable semaphore library named psem
.
In the module-4/mandatory/psem/psem.h
header file you find the documentation of the
portable semaphore API.
A small example program that demonstrates how to use the sempaphores provided by
the psem
library.
#include "psem.h"
int main(void) {
// Create a new semaphore and initialize the semaphore counter to 3.
psem_t *sem = psem_init(3);
// Wait on the semaphore.
psem_wait(sem);
// Signal on the semaphore.
psem_signal(sem);
// Destroy the semaphore (deallocation)
psem_destroy(sem)
}
In module-4/mandatory/src/psem_test.c
you find a complete example program with
two threads (main and a pthread) that synchronize their execution using a psem
semaphore.
In the terminal, navigate to the module-4/mandatory
directory. Use
make to compile the program.
$ make
Run the program from the terminal.
$ ./bin/psem_test