概述:
sem用于常用于资源管理、同步。
头文件:#include <semaphore.h>
接口:
【定义】
sem_t sem_rd;
【初始化】
int sem_init(sem_t *sem,int pshared,unsigned int value); //返回值:正常返回0
【等待信号量】
int sem_wait(sem_t *sem); //信号量值--
【释放信号量】
int sem_post(sem_t *sem); //sem值++
【获取信号量值】
int sem_getvalue(sem_t *sem);
【其他】
int sem_destroy(sem_t *sem);
int sem_trywait(sem_t *sem);
示例:
main函数中接收输入的数据到buff中,线程thread_print用于打印输入数据。
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/wait.h>
#include<pthread.h>
#include <semaphore.h>
sem_t sem_rd;
sem_t sem_wr;
char buff[50];
int sem_rdVal = 0;
int sem_wrVal = 0;
void GetSemValues(void)
{
sem_getvalue(&sem_rd,&sem_rdVal);
sem_getvalue(&sem_wr,&sem_wrVal);
printf("sem_rd:%d; sem_wr:%d\n",sem_rdVal,sem_wrVal);
}
void * thread_strat()
{
printf("%s(%d): thread ID:%lu\n",__func__,__LINE__,pthread_self());
while(1)
{
sem_wait(&sem_rd);
printf("%s(%d): buff:%s\n",__func__,__LINE__,buff);
sem_post(&sem_wr);
}
}
int main(void)
{
pthread_t thread_print;
int ret = 0;
sem_init(&sem_rd,0,0);
sem_init(&sem_wr,0,1);
GetSemValues();
ret = pthread_create(&thread_print, NULL,thread_strat, NULL);
if(ret != 0)
{
printf("thread creat fail!\n");
}
sleep(1);
do{
sem_wait(&sem_wr);
printf("please enter(enter 'quit' to exit):");
fgets(buff,50,stdin);
sem_post(&sem_rd);
}while(strncmp("quit",buff,4) != 0);
printf("%s(%d): exit!\n",__func__,__LINE__);
return 0;
}
参考:
https://blog.csdn.net/tomstrong_369/article/details/54312909
https://www.cnblogs.com/wuyepeng/p/9748552.html
https://www.bilibili.com/video/BV1Fs411M7d5?p=2