Linux 之 信号量
正文
sem_init函数
sem_destroy函数
sem_wait函数
sem_trywait函数
sem_timedwait函数
sem_post函数
以上6 个函数的返回值都是:成功返回0, 失败返回-1,同时设置errno。(注意,它们没有pthread前缀)
sem_init
int sem_init(sem_t *sem, int pshared, unsigned int value);
参数:
sem:信号量
pshared:取0用于线程间;取非0(一般为1)用于进程间
value:指定信号量初值
sem_destroy
int sem_destroy(sem_t *sem);
sem_wait
int sem_wait(sem_t *sem);
若信号量值>0,对其-1,为0阻塞。
sem_trywait
int sem_trywait(sem_t *sem);
若信号量值>0,对其-1,为0直接返回。
sem_timedwait
int sem_timedwait(sem_t *sem, const struct timespec *abs_timeout);
若信号量值>0,对其-1,为0阻塞,超时返回。
sem_post
int sem_post(sem_t *sem);
对信号量值+1。
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<string.h>
#include<sys/stat.h>
#include<sys/types.h>
#include<errno.h>
#include<semaphore.h>
#include<pthread.h>
sem_t source;
sem_t mutex;
int total = 10000;
void str_error()
{
const char * str = strerror(errno);
write(STDERR_FILENO,str,sizeof(str));
exit(-1);
}
void* fun(void* arg)
{
while(1)
{
sem_wait(&mutex);
if(total == 0)
{
sem_post(&mutex);
return NULL;
}
sem_wait(&source);
printf("thread[%ld] used %d\n",pthread_self(),total--);
sem_post(&mutex);
}
return NULL;
}
int main()
{
sem_init(&source,0,total);
sem_init(&mutex,0,1);
pthread_t fd[2];
for(int i=0;i<2;i++)
{
if(pthread_create(&fd[i],NULL,fun,NULL) != 0)
str_error();
}
for(int i=0;i<2;i++)
{
pthread_join(fd[i],NULL);
}
sem_destroy(&source);
sem_destroy(&mutex);
}