#include <semaphore.h>
int sem_wait(sem_t *sem);
int sem_trywait(sem_t *sem);
typedef struct {
...
} sem_t; /*opaque POSIX.4 semaphore*/
If at the time of a call to either sem_wait() or sem_trywait(), the value of sem is positive, these functions decrement the value of the semaphore, return immediately, and allow the calling process to continue.
If the semaphore’s value is 0:
/* cc [ flag ... ] file ... -lposix4 -lthread [ library ... ] */
#include <errno.h>
#define TELLERS 10
sem_t bank_line; /* semaphore */
int banking_hours(), deposit_withdrawal;
void *customer(), do_business(), skip_banking_today();
thread_t tid;
...
sem_init(&bank_line,TRUE,TELLERS);/* 10 tellers available */
while(banking_hours())
thr_create(NULL, NULL, customer, (void *)deposit_withdrawal, THREAD_NEW_LWP,
&tid);
...
void *
customer(deposit_withdrawal)
void *deposit_withdrawal;
{
int this_customer, in_a_hurry = 50;
this_customer = rand() % 100;
if (this_customer == in_a_hurry) {
if (sem_trywait(&bank_line) != 0)
if (errno == EAGAIN) { /* no teller available */
skip_banking_today(this_customer);
return;
} /*else go immediately to available teller & decrement bank_line*/
}
else
sem_wait(&bank_line); /* wait for next teller, then proceed, and decrement
bank_line */
do_business((int *)deposit_withdrawal);
sem_post(&bank_line); /* increment bank_line;
this_customer’s teller
is now available */
}
sem_post(3R) increments the semaphore upon its successful return.