John Doucette
John Doucette

Reputation: 4520

Combination Semaphore and Spin Lock in C?

Is it possible to build a sort of combined semaphore/spin lock in C?

That is, I want a thread control structure which supports:

For example in a program like this:

Parent:

while(something){
    //do some stuff here.
    sem_post(child_sem);
    sem_wait(parent_sem);
}

Child:

while(something_else){
    sem_wait(child_sem);
    //do some other stuff here.
    sem_post(parent_sem);

}

I would like the parent to unblock if the child fails to set parent_sem within 5 seconds, but also to unblock before 5 seconds have passed if the child has set parent_sem early, while minimizing the number of CPU cycles expended checking and re-checking the state of parent_sem over those 5 seconds. I know I can do this with a spin lock, but setting the waiting period to be high (i.e. 1 second) means wasting almost 1 second most of the time. Setting it to be low (e.g. 100ms) means doing 50 checks in the event the child times out. Neither of these is a nice solution.

Upvotes: 1

Views: 522

Answers (1)

Shahbaz
Shahbaz

Reputation: 47533

This is exactly what timed locks are for. Depending on your library, they may or may not be available.

Your example:

Parent:

while(something){
    //do some stuff here.
    sem_post(child_sem);
    while (sem_timed_wait(parent_sem, MAX_WAIT_TIME) == TIMEOUT)
        // check whether you should still continue waiting
}

Child:

while(something_else){
    while (sem_timed_wait(child_sem, MAX_WAIT_TIME) == TIMEOUT)
        // check whether you should still continue waiting
    //do some other stuff here.
    sem_post(parent_sem);
}

I have used this method to increase robustness of my threads. That is, you don't want your threads to be blocked indefinitely, because there may be an error and you want to terminate them, or you may simply want to ask them to exit. On the other hand you would want to wake up as soon as possible.

This solution satisfies both conditions.

Upvotes: 2

Related Questions