使用信号量实现进程间同步

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 }

 

转载于:https://www.cnblogs.com/GuanghuiLiu/p/8485404.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值