信号量的学习
不多说直接上代码
sem_wait部分的代码:
#include <stdio.h>
#include <stdlib.h>
#include <semaphore.h>
#include <fcntl.h>
#include <errno.h>
#include <string.h>
#include <limits.h>
int main()
{
unsigned int val;
//从配置文件中读取要监控的项目位置
sem_t* sem = sem_open("/sem222",O_CREAT|O_RDWR);
if(sem == SEM_FAILED)
{
if(errno == EEXIST)
{
printf("%s\n",strerror(errno));
exit(-1);
}
printf("%s\n",strerror(errno));
exit(-1);
}
int value;
value = 0;
sem_getvalue(sem,&value);
sem_wait(sem);
printf("sem:%d\n",value);
sem_close(sem);
}
唤醒信号量的代码:
//
// Created by zhanglei on 19-8-7.
//
#include <pthread.h>
#include <strings.h>
#include <stdio.h>
#include <semaphore.h>
#include <fcntl.h>
#include <errno.h>
#include <string.h>
#include <stdlib.h>
pthread_rwlock_t lock = PTHREAD_RWLOCK_INITIALIZER;
#define THREAD_NUM 2
#define NUM 20
int global_number = 0;
int main()
{
sem_t* sem = sem_open("/sem222",O_RDWR|O_CREAT);
if(sem ==SEM_FAILED)
{
printf("%s\n",strerror(errno));
exit(-1);
}
sem_post(sem);
}
然后使用命令进行编译
gcc main.cpp -o main -pthread
gcc demoOne.c -o demoOne -pthread
当我们打开两个
sudo ./main
的时候然后我们调用
sudo ./demoOne
发现必须要调用两次demoOne程序才会复位
为什么呢? 因为两个进程争抢信号,而且又保持了原子性,当第一个进程+1后立马会-1 消除掉,这时候第二个进程的信号还是维持在0的部分,所以必须要调用两次sem_post