tilefrae
tilefrae

Reputation: 163

Use semaphore in C

I'm learning how to use semaphore in C (linux).

I would like to ask you:

How to determine whether the order will be executed immediately , or will you wait?

Example I take to sleeping barber:

In function:

    void *customer(void *number) {
    int num = *(int *)number;

    // Leave for the shop and take some random amount of
    // time to arrive.
    printf("Customer %d leaving for barber shop.\n", num);
    randwait(5);
    printf("Customer %d arrived at barber shop.\n", num);

    // Wait for space to open up in the waiting room...
    sem_wait(&waitingRoom);
    printf("Customer %d entering waiting room.\n", num);

    // Wait for the barber chair to become free.
    sem_wait(&barberChair);

    // The chair is free so give up your spot in the
    // waiting room.
    sem_post(&waitingRoom);

    // Wake up the barber...
    printf("Customer %d waking the barber.\n", num);
    sem_post(&barberPillow);

    // Wait for the barber to finish cutting your hair.
    sem_wait(&seatBelt);

    // Give up the chair.
    sem_post(&barberChair);
    printf("Customer %d leaving barber shop.\n", num);
}

On line sem_wait(&waitingRoom); is possible check waiting - true false?

I mean:

int time = sem_wait(&waitingRoom);
if(time != 0)
 printf("YOU MUST WAIT!");

OR

   int i = isSemaphoreFree()...

I hope, you understand me, sorry for my english :-)

Upvotes: 0

Views: 1454

Answers (1)

James Anderson
James Anderson

Reputation: 27488

Take a look at sem_trywait() sem_... docs

This will return immediately with an error if the semaphore is currently blocked.

Upvotes: 1

Related Questions