操作系统学习同步与互斥例题:理发师问题

理发师问题

# include <stdio.h>
# include <stdlib.h>
# include <time.h>
# include <sys/types.h>
# include <pthread.h>
# include <semaphore.h>
# include <string.h>
# include <unistd.h>

//semaphores
sem_t  mutex,barbers,customers;
int waiting;

struct data {
    
    
    int id;
};

//理发师
void* Barbers(void* param) {
    
    
    while(1){
    
    
        int id = ((struct data*)param)->id;
        sem_wait(&customers);
        sem_wait(&mutex);
        waiting--;
        printf("    waiting-1:------%d\n",waiting);
        sem_post(&mutex);
        sem_post(&barbers);
        printf("BARBERS-CUT\n");
        printf("        waiting\n");
        sleep(5);
        // pthread_exit(0);
    }
}

//顾客
void* Customers(void* param) {
    
    
    int id = ((struct data*)param)->id;
    sem_wait(&mutex);
    if(waiting<10){
    
    
        waiting++;
        printf("    waiting+1:------%d\n",waiting);
        sem_post(&mutex);
        sem_post(&customers);
        sem_wait(&barbers);
        printf("%d CUSTOMERS-CUT\n",id);

    }
    else
        printf("FULL\n");
        sem_post(&mutex);
    // pthread_exit(0);
}

int main() {
    
    
    //pthread
    pthread_t tid; // the thread identifier

    pthread_attr_t attr; //set of thread attributes

    /* get the default attributes */
    pthread_attr_init(&attr);

    //initial the semaphores
    sem_init(&mutex, 0, 1);
    sem_init(&customers, 0, 0);
    sem_init(&barbers, 0, 0);
    waiting = 0;

    int id = 0;
    while(scanf("%d", &id) != EOF) {
    
    

        char role;      //producer or consumer
        scanf("%c", &role);
        struct data* d = (struct data*)malloc(sizeof(struct data));
        d->id = id;
        if(role == 'B') {
    
    
            printf("    BARBER\n");
            pthread_create(&tid, &attr, Barbers, d);
        }
        else if(role == 'C') {
    
    
            printf("    %d CUSTOMER\n",id);
            pthread_create(&tid, &attr, Customers, d);
        }
    }

    //信号量销毁
    sem_destroy(&mutex);
    sem_destroy(&barbers);
    sem_destroy(&customers);
    return 0;
}
/*
1 C
2 B
3 C
4 C

*/

猜你喜欢

转载自blog.csdn.net/qq_54226199/article/details/129867423