interprocess communication (3)--semaphore

Source: Internet
Author: User

the realization of the signal volume and the simple mutual exclusion lock

Semaphore: Unlike pipeline and Message Queuing, semaphores can be said to be a counter, it is used to control the multi-process access to critical resources, it is a PV operation, p is a minus one operation, it is used to obtain the use of critical resources, if less than zero can be accessed, or suspend wait, V for the addition of an operation, The process is executed upon completion of his visit and is used to return the use of the resource.

Atomic operation: PV plus one minus one is atomic operation that is, plus one minus one corresponding to the computer language only one operation, if not the design will cause both sides of the simultaneous application caused by the failure of normal execution.

Int semget (KEY_T&NBSP;KEY,&NBSP;INT&NBSP;NSEMS,&NBSP;INT&NBSP;SEMFLG); This is the semaphore acquisition function, Nsmes represents the number of semaphore sets to be requested, The other two are very familiar. the semid_ds data structure is defined in <sys/sem.h> as  follows:           struct semid_ds {                struct ipc_perm  sem_perm;  /* ownership and permissions */                time_t           sem_otime; /* Last semop time */                time_t           sem_ctime; /* Last change time */                unsigned short  sem_nsems; /* no. of  semaphores in set */           };  Above is a structure of the computer core designed for each semaphore set. Each semaphore    int semop (int semid, struct sembuf *sops, unsigned  Nsops);   This function is the function used to perform the PV operation,            struct  sembuf{           unsigned short sem_ num;  /* semaphore number */            short          sem_op;   /*  semaphore operation */           short           sem_flg;  /* operation flags */ &nbsP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;};//This structure is a structure used to operate each signal, Sem_num represents              to operate on the first few signals (array subscripts), Sem_op indicates which of the PV operations to perform.

*SEM_FLG (); It is an object of the SEMBUF structure in Semop, and it is used to select a type of execution

There are 0 blocking waits, ipc_nowait (non-blocking wait), Sem_undo (as its name does nothing, all PV operations performed in this process are reverted to the value of the semaphore at the end of the process to avoid errors in this process)



The semaphore implements the code for a mutex lock

The contrast shows that there is no interleaving of the AB because of mutually exclusive access to the process

650) this.width=650; "src=" Http://s3.51cto.com/wyfs02/M02/7F/01/wKioL1cPmNuhDS3SAADcoTGQFso876.png "title=" Untitled. png "Width=" "height=" "border=" 0 "hspace=" 0 "vspace=" 0 "style=" width:700px;height:110px; "alt=" Wkiol1cpmnuhds3saadcotgqfso876.png "/>

Comm.c

  1  #include "comm.h"   2 union semun {  3      int  val;    /* value for setval */  4      struct semid_ds *buf;    /* buffer for  IPC_STAT, IPC_SET */  5     unsigned short   *array;  /* array for getall, setall */  6      struct seminfo  *__buf;  /* Buffer for IPC_INFO*/   7 };  8   9 static int comm_get_sem (Int msems,int  flag)  10 { 11     key_t _sem_key=ftok (_PATH_,_PROJ_ID);  12     if (_sem_key<0)  13     { 14       &nbSp;  perror ("Ftok"); 15         return -1;  16     } 17     int sem_id=semget (_sem_key, Msems,flag);  18     if (sem_id<0)  19     {  20         return -1; 21     }  22     return sem_id; 23  24 } 25 int  Creat_sem (int nsems)  26 { 27     umask (0); 28      return comm_get_sem (nsems,ipc_creat| ipc_excl|0666);  29 } 30  31 int get_sem ()  32 { 33      return comm_get_sem (0,ipc_creat);  34 } 35 int init_sem ( Int semid,int whitch) &NBSP;36&NBSP;{&NBSP;37&NBSP;&NBSP;&NBSP;&NBsp; union semun _semnu; 38     _semnu.val=1; 39      int ret = semctl (SEMID,WHITCH,SETVAL,_SEMNU); 40      return ret; 41 } 42 static int sem_op (int semid,struct  Sembuf *sops,unsigned nsops)  43 { 44          return semop (Semid,sops,nsops);  45 } 46 int p_sem_op (Int semid,int  which)  47 { 48     struct  sembuf sem; 49      sem.sem_op=-1; 50     sem.sem_num=which; 51      sem.sem_flg=sem_undo; 52     return sem_op ( semid,&sem,1);  53 } 54  55 int v_sem_op (Int semid,int which)  56 { 57     struct sembuf sem; 58     sem.sem_op=1;  59     sem.sem_num=which; 60     sem.sem_flg=sem_ Undo; 61     return sem_op (semid,&sem,1); 62 } 63  Int destroy_sem (int sem_id)  64 { 65     int ret = Semctl (Sem_id,0,ipc_rmid,null);  66  67     if (ret <0) { 68              return -1; 69          } 70     return 0; 71  }

Sem_socket.c

  1  #include "comm.h"   2   3 int main ()   4 {   5     int sem_id=creat_sem (1);  6      int ret=init_sem (sem_id,0);   7     pid_t id=fork ();   8     if (id<0)   9     { 10          perror ("fork");  11     }else  if (id==0) { 12             int  sem_id=get_sem (); 13              while (1) { 14         //           printf ("child begin:\n"); 15          p_sem_op (sem_id,0);   16         printf ("A"); 17          fflush (stdout);  18         sleep (2);  19         printf ("A"); 20          fflush (stdout); 21          Sleep (1);  22         v_sem_op (sem_id,0); 23          } 24     }else{ 25          while (1)  26              { 27              //sleep (Ten); 28              P_sem_op (sem_id,0);  29              printf ("B"); 30              fflush (stdout); 31              sleep (1); 32              printf ("B"); 33              fflush (stdout); 34              sleep (2); 35              v_sem_op (sem_id,0);  36         } 37          waitpid (id,0,null); 38      } 39  40  41     return 0; 42 } "sem_ Socket.c "&NBSP;42L,&NBSP;588C&NBSP;&Nbsp;                                                                       1,1            Top


This article is from the "Traces" blog, be sure to keep this source http://wpfbcr.blog.51cto.com/10696766/1763929

interprocess communication (3)--semaphore

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.