definition : Semaphore is a counter that is used to control access to shared data objects by multiple processes. In order to obtain a shared resource, the process needs to perform the following actions
Signal usage steps:
1: Initialize semaphore---->int sem_init (sem_t *sem, int pshared, unsigned int value);
2: Apply for resources, and do a reduction in the amount of signal----->int sem_wait (sem_t *sem);
3: Release the resources and add an operation to the semaphore------>int sem_post (sem_t *sem);
Test Program
#include <sys/types.h>
#include <stdio.h>
#include <string.h>
#include <sys/ipc.h>
#include <sys/sem.h>
#include <stdio.h>
#include <pthread.h>
#include <semaphore.h>
int num = 0;
void *func1 (void *sem)
{
int sval;
Srand ((unsigned) time (0));
While (1)
{
int r = rand ()% 3;
sleep (R);
if (0 = = sem_wait (SEM))
{
num++;
printf ("1 Get it\n");
}
sleep (R);
printf ("1 Pass the ball\n");
sem_post (SEM);
}
}
void *func2 (void *sem)
{
int sval;
Srand ((unsigned) time (0));
While (1)
{
int r = rand ()% 3;
sleep (R);
if (0 = = sem_wait (SEM))
{
num++;
printf ("2 Get it\n");
}
sleep (R);
printf ("2 Pass the Ball\n");
sem_post (SEM);
}
}
void *func3 (void *sem)
{
int sval;
Srand ((unsigned) time (0));
While (1)
{
int r = rand ()% 3;
sleep (R);
if (0 = = sem_wait (SEM))
{
num++;
printf ("3 Get it\n");
}
sleep (R);
printf ("3 Pass the Ball\n");
sem_post (SEM);
}
}
int main ()
{
sem_t sem;
int pshared = 1;
pthread_t tid;
pthread_attr_t attr;
Sem_init (&sem,pshared,1);
if (0! = Pthread_attr_init (&attr))
perror ("Pthread_attr_init");
pthread_attr_setdetachstate (&attr,pthread_create_detached); Setting the Detach property
printf ("start\n");
if (0! = pthread_create (&tid,&attr,func1,&sem))
perror ("Pthread_create");
if (0! = pthread_create (&tid,&attr,func2,&sem))
perror ("Pthread_create");
if (0! = pthread_create (&tid,&attr,func3,&sem))
perror ("Pthread_create");
While (1)
{
if (num = =)
{
Break ;
printf ("finshed\n");
}
}
return 0;
}
Signal volume of interprocess communication