Title: COMP309/509 - Lecture 10 class: middle, center, inverse

COMP309/509 - Parallel and Distributed Computing

Lecture 12 - Semaphores

By Mitchell Welch

University of New England


Reading


Summary


Abstract Semaphore Concepts


Abstract Semaphore Concepts


Abstract Semaphore Concepts


Abstract Semaphore Concepts


Abstract Semaphore Concepts


Abstract Semaphore Concepts


User-level Semaphores


User-level Semaphores


UNIX System V Semaphores

ipcs -s -a

UNIX System V Semaphores

ipcrm -s <semid>

UNIX System V Semaphores

#include <sys/types.h>
#include <sys/ipc.h>

key_t ftok(const char *pathname, int pin);

UNIX System V Semaphores


#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/sem.h>
int semget(key_t key, int nsems, int semflg);

UNIX System V Semaphores

int semctl(int semid, int semnum, int cmd, ...);
int semop(int semid, struct sembuf *sops, unsigned nsops);

UNIX System V Semaphores

int semget(
           key_t key,    /* the key or IPC_PRIVATE */
           int nsems,    /* the number of semaphores in the set      */
           int semflg    /* IPC_CREAT, IPC_EXCL, or file permissions */
          );

UNIX System V Semaphores

int semctl(
           int semid,    /* the id of the semaphore set              */
           int semnum,   /* the element of the set we are focused on */
           int cmd,      /* one of the ten (10) possible operations  */
           ...
          );

UNIX System V Semaphores


UNIX System V Semaphores

  semctl(semid, 0, IPC_RMID);
  int retval;
  union semun arg;  /* copy the definition from the man pages  */
  unsigned short values[4] = { 0, 0, 0, 0};
  arg.array = values;
  retval = semctl(semid, 0, SETALL, arg);

UNIX System V Semaphores

 int semop(
           int semid,            /* the id of the semaphore set      */
           struct sembuf *sops,  /* an array of operations           */
           unsigned nsops        /* the length of the array          */
      );
unsigned short sem_num;  /* semaphore number from 0 upto nsems - 1        */
short sem_op;            /* the aamout to add to  the value               */
short sem_flg;           /* flags:  0, IPC_NOWAIT or  SEM_UNDO            */

UNIX System V Semaphores

 int i, retval;
 struct sembuf ops[4];
 for(i = 0; i < 4; i++){
  ops[i].sem_num = i;
  ops[i].sem_op = 1;
  ops[i].sem_flg = 0;
 }
 retval = semop(semid, ops, 4);

UNIX System V Semaphores

 int i, retval;
 struct sembuf ops[4];
 for(i = 0; i < 4; i++){
  ops[i].sem_num = i;
  ops[i].sem_op = -1;
  ops[i].sem_flg = 0;
 }
 retval = semop(semid, ops, 4);

The Dining Philosophers


The Dining Philosophers


Producers and Consumers (Again)


A Final Example


class: middle, center, inverse

Questions?


Summary


Reading