使用信號量實現進程間同步


1、進程a ;

     完成信號量的創建和設置;

     做定時器,每1s sem_post 信號量一次;

 1 #include <stdio.h>
 2 #include <fcntl.h>
 3 #include <stdlib.h>
 4 #include <unistd.h>
 5 #include <semaphore.h>
 6 
 7 //利用select函數完成一個定時器的功能;
 8 void setTimer(int seconds, int microseconds)
 9 {
10         struct timeval temp;
11         temp.tv_sec = seconds;
12         temp.tv_usec = microseconds;
13         select(0, NULL, NULL, NULL, &temp);
14         return ;
15 }
16 
17 int main()
18 {
19     sem_t* a;
20     int er=0;
21 
22     sem_unlink("share_data"); //若內存中已經存在名為“sem_test”的信號量,則將其刪除;
23 
24     // 創建一個名為"sem_test"的信號量,並將其值初始化為1,a為sem_t型指針,指向該信號量;
25     a=sem_open("share_data", O_CREAT ,(S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH), 1);
26     if(NULL==a)
27     {
28         printf("sem_open failure!\n");
29     }
30 
31     //將該信號量賦為1,且為進程間共享型信號量;
32     sem_init(a,1,0);
33 
34     //獲取當前信號量的值;
35     sem_getvalue(a, &er);
36     while(1)
37     {
38          if(er==0)
39          {
40              sem_post(a);
41          }
42          setTimer(1,0);
43          sem_getvalue(a, &er);
44          printf("%d\n",er);
45     }
46     return 0;
47 }

2:進程b;

    當信號量被 a 進程進行sem_post后,進程b由阻塞態變為可執行;

 1 /*
 2  ============================================================================
 3  Name        : share_data_a.c
 4  Author      : 
 5  Version     :
 6  Copyright   : Your copyright notice
 7  Description : Hello World in C, Ansi-style
 8  ============================================================================
 9  */
10 
11 #include <stdio.h>
12 #include <fcntl.h>
13 #include <stdlib.h>
14 #include <unistd.h>
15 #include <semaphore.h>
16 
17 int main()
18 {
19     sem_t* a;
20 
21     //sem_open()函數第2個參數為0,表示打開已存在的名為"share_data"的信號量;
22 
23     a=sem_open("share_data", 0, (S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH), 1);
24 
25     if(NULL==a)
26     {
27         printf("sem_open failure!\n");
28     }
29     int i=0,er;
30     while(1)
31     {
32       sem_wait(a);        //當進程 a 完成sem_post動作時,該進程開始繼續執行;
33       printf("i = %d\n",i++);
34     }
35     return 0;
36 }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM