LINUX信号量实现对公共数据的读写

0x00.信号量的作用
  信号量(Semaphore),有时被称为信号灯,是在多线程环境下使用的一种设施,
是可以用来保证两个或多个关键代码段不被并发调用。在进入一个关键代码段之前,
线程必须获取一个信号量;一旦该关键代码段完成了,那么该线程必须释放信号量。
其它想进入该关键代码段的线程必须等待直到第一个线程释放信号量。为了完成这个过程,
需要创建一个信号量VI,然后将Acquire Semaphore VI以及Release Semaphore VI分别放置在每个关键代码段的首末端。确认这些信号量VI引用的是初始创建的信号量。

0x01.LINUX信号量要使用到的函数

#include <semaphore.h>

//初始化信号结构体
int sem_init(sem_t *sem, int pshared, unsigned int value);

int sem_post(sem_t *sem); //信号量+1
int sem_wait(sem_t *sem); //信号量-1

int sem_destroy(sem_t *sem); //销毁信号结构体

 


0x02.信号量示例代码

 1 sem_t sem;
 2 int count_num = 0;
 3 void* ThreadFunc(void* argc);
 4 
 5 int main(int argc, char* argv[])
 6 {
 7     int status = sem_init(&sem, 0, 0);
 8     pthread_t pid;
 9 
10     if(-1 == status)
11     {
12         perror("main()->sem_init()");
13         exit(1);
14     }
15 
16     status = pthread_create(&pid, NULL, ThreadFunc, NULL);
17     if(0 != status)
18     {
19         perror("main()->pthread_create()!");
20         exit(1);
21     }
22 
23     //主线程阻塞点,通过信号量进行数数
24     while(count_num < 10)
25     {
26         if((count_num % 2) != 0)
27         {
28             printf("%d ", count_num);
29             ++count_num;
30         }
31 
32         sem_post(&sem);
33     }
34 
35     status  = pthread_join(pid, NULL);
36     if(0 != status)
37     {
38         perror("main()->pthread_join()");
39         exit(1);
40     }
41 
42     sem_destroy(&sem);
43 
44     return 0;
45 }
46 
47 //subthread count numbers
48 void* ThreadFunc(void* argc)
49 {
50     //子线程阻塞点
51     while(count_num < 10)
52     {
53         if((count_num % 2) == 0)
54         {
55             printf("%d ", count_num);
56             ++ count_num;
57         }
58         sem_wait(&sem);
59     }
60 
61     pthread_exit(NULL);
62 }

 

0x03. 遇到的坑
阻塞点没写对,造成数数一直有问题,写代码要先弄清楚业务逻辑

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值