Obscure pthread_mutex questions

I’ve been having some trouble with an encapsulation
of pthread_mutex, and I have a few rather obscure questions.

  1. If the current thread has a recursive mutex locked,
    can that thread destroy it with pthread_mutex_destroy,
    or will pthread_mutex_destroy fail with an EBUSY?

  2. What, if anything, does pthread_mutexattr_destroy
    actually do?

  3. What’s the proper procedure for destroying a mutex
    that has threads waiting? pthread_mutex_destroy
    will return EBUSY in that situation, right? This comes up
    in exception processing, when the destructor for a
    mutex is called and there might be threads waiting.
    Ideally, I’d like all the waiting threads to get an
    error return from their pthread_mutex_wait call.
    Is there a way to do that?

John Nagle
Animats

John Nagle <nagle@downside.com> wrote:

  1. If the current thread has a recursive mutex locked,
    can that thread destroy it with pthread_mutex_destroy,
    or will pthread_mutex_destroy fail with an EBUSY?

According to POSIX (normal, non-recursive mutexes) the mutex
must be unlocked before it can be destroyed, else it is EBUSY.
(Actually “Attempting to destroy a locked mutex results in
undefined behaviour” :slight_smile: For recrusive, it will also be EBUSY
if locked (count ignored in kernel processing).

  1. What, if anything, does pthread_mutexattr_destroy
    actually do?

Under the QNX6 implementation, nothing (“return(EOK);”).
POSIX suggests that you could take this opportunity to
stuff the fields of the attr with invalid values to make
sure it isn’t re-used. Presumably if pthread_mutexattr_init()
had some non-trivial initialisation (it doesn’t) this is
where you’d clean up after it.

  1. What’s the proper procedure for destroying a mutex
    that has threads waiting? pthread_mutex_destroy
    will return EBUSY in that situation, right?

This I’m not sure about. Destroying the mutex is something
that should be handled from a higher level using some
other/implied synchronisation (in a similar fashion to there
being some coordination in the initial creation of the mutex).
Like mutexes associated with a filesystem, I init on the mount
and destroy on the unmount (because at that point I have
verified there are no open files and hence no-one is using it).

in exception processing, when the destructor for a
mutex is called and there might be threads waiting.

Doesn’t this indicate some kind of design error, if threads
are using an object during/past its destruction (it shoudln’t
be being destroyed just yet)?