Posix 信号量

作用

信号量的值为0或正整数,就像红灯与绿灯,用于指示当前是否可以接受任务.
信号量对进程和线程都适用.
gcc编译时需加-lpthread

基本函数

信号量的相关函数与标准文件函数非常相似,可以理解文件的读写,只是读写对象不同而已

#include <semaphore.h>
sem_t *sem_open(const char *name,int oflag,...
        /* mode_t mode,unsigned int value */);
int sem_close(sem_t *sem);
int sem_unlink(const char *name);
int sem_wait(sem_t *sem);
int sem_trywait(sem_t *sem);
int sem_post(sem_t *sem);
int sem_getvalue(sem_t *sem,int *valp);

例子

#include "./unpipc.h"
#include <semaphore.h>
#include <pthread.h>
 
#define NBUFF 10
#define SEM_MUTEX "/mutex"
#define SEM_NEMPTY "/empty"
#define SEM_NSTORED "/nstored"
 
int nitems;
struct {
    int buff[NBUFF];
    sem_t *mutex,*nempty,*nstored;
} shared;
 
void *produce(void *), *consume(void *);
 
int main(int argc,char *argv[]){
    pthread_t tid_produce,tid_consume;
 
    if(argc != 2)
        err_quit("usage: sem <#items>");
    nitems=atoi(argv[1]);
 
    shared.mutex=sem_open(SEM_MUTEX,O_CREAT|O_EXCL,0644,1);
    shared.nempty=sem_open(SEM_NEMPTY,O_CREAT|O_EXCL,0644,NBUFF);
    shared.nstored=sem_open(SEM_NSTORED,O_CREAT|O_EXCL,0644,0);
 
    pthread_setconcurrency(2);
    pthread_create(&tid_produce,NULL,produce,NULL);
    pthread_create(&tid_consume,NULL,consume,NULL);
 
    pthread_join(tid_produce,NULL);
    pthread_join(tid_consume,NULL);
 
    sem_unlink(SEM_MUTEX);
    sem_unlink(SEM_NEMPTY);
    sem_unlink(SEM_NSTORED);
    exit(0);
}
 
void *
produce(void *arg){
    int i;
 
    for(i=0;i<nitems;i++){
        sem_wait(shared.nempty);
        sem_wait(shared.mutex);
        shared.buff[i%NBUFF]=i;
        sem_post(shared.mutex);
        sem_post(shared.nstored);
    }
    return(NULL);
}
void *
consume(void *arg){
    int i;
 
    for(i=0;i<nitems;i++){
        sem_wait(shared.nstored);
        sem_wait(shared.mutex);
        if(shared.buff[i%NBUFF] != i)
            printf("buff[%d]=%d
",i,shared.buff[i%NBUFF]);
        sem_post(shared.mutex);
        sem_post(shared.nempty);
    }
    return(NULL);
}
原文地址:https://www.cnblogs.com/cfans1993/p/5813725.html