CSE 411 - additional notes

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

POSIX semaphores  ("man sem_init" and so on)
#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);

Excerpt from Solaris  /usr/include/semaphore.h
typedef struct {
  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;
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.

POSIX mutex variables

#include <pthread.h>
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.

POSIX condition variables You can find the definition of pthread_mutex_t and pthread_cond_t in /usr/include/sys/types.h which is included by /usr/include/pthread.h.

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?