The programming assignments will use the POSIX functions for threads and semaphores. The man pages cited here refer to Sun Solaris, and may be different on other systems. The POSIX functions themselves are defined in a standard way and should work correctly on many different systems.
POSIX semaphores
#include <semaphore.h>Excerpt from Solaris /usr/include/semaphore.h
int sem_init(sem_t *sem, int pshared, unsigned int value);
int sem_wait(sem_t *sem); /* P(sem), wait(sem) */
int sem_post(sem_t *sem); /* V(sem), signal(sem) */int sem_getvalue(sem_t *sem, int *sval);
int sem_trywait(sem_t *sem);int sem_destroy(sem_t *sem); /* undo sem_init() */
/* named semaphores - these are less useful here */
sem_t *sem_open( ... );
int sem_close(sem_t *sem);
int sem_unlink(const char *name);
typedef struct {An example is posted, with a discussion "Is it better to be smart or careful?", and a suggestion about checking return values to detect errors.
uint32_t sem_count; /* semaphore count */
uint16_t sem_type;
uint16_t sem_magic;
upad64_t sem_pad1[3]; /* reserved for a mutex_t */
upad64_t sem_pad2[2]; /* reserved for a cond_t */
} sem_t;
POSIX mutex variables
#include <pthread.h>POSIX condition variables
int pthread_mutex_init(pthread_mutex_t *mutex, NULL);
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
int pthread_mutex_lock(pthread_mutex_t *mutex);
int pthread_mutex_unlock(pthread_mutex_t *mutex);int pthread_mutex_trylock(pthread_mutex_t *mutex);
int pthread_mutex_destroy(pthread_mutex_t *mutex);
etc.
int pthread_cond_timedwait( ... );
int pthread_cond_broadcast(pthread_cond_t *cond);
int pthread_cond_destroy(pthread_cond_t *cond);
etc.
pthread_mutex_lock(&A);
pthread_cond_wait(&B, &A);
/* A is unlocked while waiting */
/* A is locked after waiting */
pthread_mutex_unlock(&A);
pthread_mutex_lock(&A);
pthread_cond_signal(&B);
pthread_mutex_unlock(&A);
Test your understanding:
Why do the types pthread_mutex_t and pthread_cond_t have a convenient initalizer, such as PTHREAD_MUTEX_INITIALIZER , but the type sem_t does not?