信号量

信号量例子

#include 
#include 
#include 
#include 

sem_t remain, apple, pear, mutex;
static unsigned int vremain = 20, vapple = 0, vpear = 0;

void *father(void *);
void *mother(void *);
void *son(void *);
void *daughter(void *);
void print_sem();


int main()
{
    pthread_t fa, ma, so, da;
    sem_init(&remain, 0 , 20);
    sem_init(&apple, 0, 0);
    sem_init(&pear, 0, 0);
    sem_init(&mutex, 0, 1);
    pthread_create(&fa, NULL, &father, NULL);
    pthread_create(&ma, NULL, &mother, NULL);
    pthread_create(&so, NULL, &son, NULL);
    pthread_create(&da, NULL, &daughter, NULL);

    while(1) {
        sem_wait(&mutex);
        printf("apple: %u, pear: %u, left: %u\n", vapple, vpear, vremain);
        sem_post(&mutex);
        sleep(1);
    }
}

void *father(void *arg)
{
    while(1) {
        sem_wait(&remain);
        sem_wait(&mutex);
        printf("father: put before, left = %u, apple = %u\n", vremain, vapple);
        vremain --;
        vapple ++;
        printf("father: put after, left = %u, apple = %u\n\n", vremain, vapple);
        sem_post(&mutex);
        sem_post(&apple);
        sleep(1);
    }
}

void *son(void *arg)
{
    while(1) {
        sem_wait(&apple);
        sem_wait(&mutex);
        printf("son: take before, left = %u, apple = %u\n", vremain, vapple);
        vremain ++;
        vapple --;
        printf("son: put after, left = %u, apple = %u\n\n", vremain, vapple);
        sem_post(&mutex);
        sem_post(&remain);
        sleep(3);
    }
}

void *mother(void *arg)
{
    while(1) {
        sem_wait(&remain);
        sem_wait(&mutex);
        printf("mother: put before, left = %u, pear = %u\n", vremain, vpear);
        vremain --;
        vpear ++;
        printf("mother: put after, left = %u, pear = %u\n\n", vremain, vpear);
        sem_post(&mutex);
        sem_post(&pear);
        sleep(3);
    }
}

void *daughter(void *arg)
{
    while(1) {
        sem_wait(&pear);
        sem_wait(&mutex);
        printf("dau: take before, left = %u, pear = %u\n", vremain, vpear);
        vremain ++;
        vpear --;
        printf("dau: take after, left = %u, pear = %u\n\n", vremain, vpear);
        sem_post(&mutex);
        sem_post(&remain);
        sleep(1);
    }
}

你可能感兴趣的:(linux)