<

Lecture #5

Administrivia

Previously on CSS 503A...

Message Passing

Interprocess Communication (cont.)

System V Message Queues

int msgid = msgget(key_t key, int msgflg);

int msgsnd(int msgid, struct msgbuf *msgp, size_t msgsz, int msgflg);

struct msgbuf {
  long mtype,
  char mtext[]
};

C-style casting wizardry: superimpose msgbuf onto your own data structure.

mtype: use pattern matching on receive.

ssize_t msgrcv(
  int msgid,
  void * msgp,  // pointer to user-allocated space
  size_t msgsz,
  long msgtype, // pattern matching: select message with this type
  int msgflg
);

System V Semaphores

API:

int semid = semget(key_t key, int nsems, int semflag);  // create/open semaphore set

int sem_op(
  int semid,
  struct sembuf *sops
  unsigned nsops
);

struct sembuf {
    unsignes short sem_num,
    short sem_op,  // >0: increment; < 0: decrement or wait; 0: wait for zero
    short sem_flag  // IPC_NOWAIT: return immediately (failure if counter is 0)
);

Shared Memory

API:

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

// create/access shared memory
int shmid = shmget(
  key_t key,
  size_t size,
  int shmflg
);

void* shmat(int shmid, const void *shmaddr, in t shmflg)

Threads

Deadlock Example

TODO: diagram

User (Green) Threads vs. Kernel Threads

Threading Issues

Posix Thread (pthreads)

#include <pthread.h>
#include <unistd.h>

// User-defined thread function
// Takes pointer arg, returns pointer value.
//     - most-general API: user-defined data
//     - requires caution: not type-safe
void *thread_func(void *param);

int pthread_create(
    pthread_t *thread,
    const pthread_attr_t *attr,
    void *(*start_routine)(void *),
    void *arg
);