Overview of semaphores: Semaphores are a process communication mechanism used to resolve synchronization and mutex issues between processes, including a variable called semaphore and a process waiting queue that waits for resources under that semaphore, as well as two atomic operations on the semaphore process (PV operation). Where the semaphore corresponds to a certain resource, take a non-negative shaping value. The semaphore value refers to the current number of available resources, and if it equals 0 it means there are currently no available resources.
The specific definition of the PV atomic operation is:
P Operation: If there are available resources (semaphore value >0), then occupy a resource (to reduce the semaphore value by one, enter the critical section code), if there is no available resources (semaphore value equals 0), it is blocked to know that the system will allocate resources to the process (into the waiting queue, until the resources turn to the process).
V Operation: If there is a process waiting for the resource in the wait queue for that semaphore, a blocking process is awakened. If no process is waiting for it, a resource is freed (the semaphore value plus one).
Semget () function
、
Semctl () function
Semop function
Code Analysis:
/*SEM_COM.C*/#include"sem_com.h"/*semaphore Initialization (Assignment) function*/intInit_sem (intSEM_ID,intinit_value) {Union Semun sem_union; Sem_union.val= Init_value;/*Init_value as the initial value*/ if(Semctl (sem_id,0, Setval, sem_union) = =-1) {perror ("Initialize Semaphore"); return-1; } return 0;}/*functions to remove semaphores from the system*/intDel_sem (intsem_id) {Union Semun sem_union; if(Semctl (sem_id,0, Ipc_rmid, sem_union) = =-1) {perror ("Delete Semaphore"); return-1; }}/*p operation function*/intSem_p (intsem_id) { structSembuf Sem_b; Sem_b.sem_num=0;/*the number of a single semaphore should be 0*/Sem_b.sem_op= -1;/*represents the P operation*/SEM_B.SEM_FLG= Sem_undo;/*system automatically releases the amount of semaphores that will remain in the system*/ if(Semop (sem_id, &sem_b,1) == -1) {perror ("P Operation"); return-1; } return 0;}/*v operation function*/intSem_v (intsem_id) { structSembuf Sem_b; Sem_b.sem_num=0;/*the number of a single semaphore should be 0*/Sem_b.sem_op=1;/*represents the V Operation*/SEM_B.SEM_FLG= Sem_undo;/*system automatically releases the amount of semaphores that will remain in the system*/ if(Semop (sem_id, &sem_b,1) == -1) {perror ("V Operation"); return-1; } return 0;}
Operation of semaphore for process communication