0
votes

Can I call semaphore.wait() within mutex_lock if in the path somehow it can be guaranteed that resource protected by the semaphore is available?

I.e. I want to do something like following:

void some_function {

    mutex_lock()
    // Do something
    if (certain_conditions == TRUE) {
        semaphore_wait()   // Guaranteed that resource is available.
                           // Can not get blocked for sure.
    } 
    // Do some more things
    mutex_unlock()

}
1
Pedantic, but if (certain_conditions = TRUE) is not what you want (use ==): please post acutal code not "something-like" code. - Weather Vane
Can I do X if I can guarantee X will work? No, because somebody on StackOverflow says you're forbidden. :D JK. I think the answer's obvious, but if I were you I'd use the trywait variant (I think all reasonable semaphore implementation should have those) and assert() success. - PSkocik
If what you claim really is true, is the mysterious missing puzzle piece that a way it can not be guaranteed to work is by releasing that mutex prior to the wait, someone else acquiring it, and thereafter breaking the warrant that the upcoming wait on this thread "can not get blocked for sure" ? Honestly, it sounds like you have a design hurdle, but with so little to go on that's just speculation. - WhozCraig
If you can guarantee that the resource protected by the semaphore is always available, then why use a semaphore to protect it? - Jim Mischel
Well, sure. It can be done. The worst that can happen is that the call will block, thus leaving the mutex acquired for an extended period. Which, granted, could lead to deadlock if for some unexpected reason the resource isn't available. But there's no language or runtime reason you can't call a sem_wait while you have a mutex. - Jim Mischel

1 Answers

1
votes

Basically, the answer to your question is:
Yes. You can call a "wait" primitive on a semaphore within a Mutex lock context.

Actually, that is something that is constantly done. Think of, for example, implementation of Message Queue IPC services with Counting Semaphores: you need to lock the Mutex protecting the queue before calling your "wait" primitive on the Counting Semaphore.

Thinking of POSIX, if you have to implement a Mailbox (typical Producer/Consumer example), you can safely and easily do it with Mutex and Condition Variables (which would be used as your Semaphores). What you want to do is nothing strange as long as you're in control of the situation.