POSIX Semaphores A Variable of Type Sem - T
POSIX Semaphores A Variable of Type Sem - T
Barbeau
POSIX Semaphores
#include <semaphore.h>
sem_t sem;
#include <semaphore.h>
int sem_init(sem_t *sem, int pshared, unsigned int value);
int sem_wait(sem_t * sem);
int sem_trywait(sem_t * sem);
int sem_post(sem_t * sem);
int sem_getvalue(sem_t * sem, int * sval);
int sem_destroy(sem_t * sem);
sem_wait suspends the calling thread until the semaphore pointed to by sem has
non-zero count. It then atomically decreases the semaphore count.
1
Advanced Linux Programming M. Barbeau
sem_getvalue stores in the location pointed to by sval the current count of the
semaphore sem.
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <string.h>
#include <errno.h>
#include <fcntl.h>
#include <pthread.h>
#include <unistd.h>
#define POSIX_SEMAPHORE
/* #define SYSV_SEMAPHORE */
#ifdef POSIX_SEMAPHORE
#include <semaphore.h>
sem_t my_sem;
#define SEMINITVALUE 1
#endif
#ifdef SYSV_SEMAPHORE
#include <sys/ipc.h>
#include <sys/sem.h>
int my_sem, semop_ret;
#define PERMS S_IRUSR | S_IWUSR
#define SEM_SET_SIZE 1
struct sembuf semwait = { 0, -1, 0 };
struct sembuf semsignal = { 0, 1, 0 };
#endif
2
Advanced Linux Programming M. Barbeau
/* function prototypes */
void *critical_section(void *);
/*
* Main program
*
*/
int main(int argc, char *argv[])
{
int n, i, error;
pthread_t threadid[MAXTHREADS];
3
Advanced Linux Programming M. Barbeau
exit(0);
}
/* entry action */
#ifdef POSIX_SEMAPHORE
if (sem_wait(&my_sem) == 1)
{
perror("Invalid semaphore");
exit(1);
}
#endif
#ifdef SYSV_SEMAPHORE
while ((semop_ret=semop(my_sem, &semwait, 1)==-1) &&
(errno == EINTR));
if (semop_ret == -1)
{
fprintf(stderr, "Semaphore decrement failed: %s\n",
strerror(errno));
}
#endif
/* critical section */
for (i=1; i < 5; i++)
4
Advanced Linux Programming M. Barbeau
{
fprintf(stdout, "%d : %d\n", myindex, i);
/* sleep for one second */
if ((n=sleep(1)) != 0)
fprintf(stderr, "interrupted, no of secs left %d\n",
n);
}
/* exit action */
#ifdef POSIX_SEMAPHORE
if (sem_post(&my_sem) == -1)
{
perror("Invalid semaphore");
exit(1);
}
#endif
#ifdef SYSV_SEMAPHORE
while ((semop_ret=semop(my_sem, &semsignal, 1)==-1) &&
(errno == EINTR));
if (semop_ret == -1)
{
fprintf(stderr, "Semaphore increment failed: %s\n",
strerror(errno));
}
#endif
/* remainder */
pthread_exit(NULL);
}