what is the correct behavior of pthread_mutex_dest

2019-07-04 04:00发布

问题:

I wrote the following minimal example:

#include <iostream>
#include <cstring>
#include <pthread.h>
#define SUCCESS 0
using namespace std;

int main() {
    int res;
    pthread_mutex_t t;
    pthread_mutex_init(&t, NULL);

    res = pthread_mutex_lock(&t);

    res = pthread_mutex_destroy(&t);
    if (res != SUCCESS)
    {
        cout << "Failed to delete: " << strerror(res) << " # " << t.__data.__lock << " " << t.__data.__nusers << endl;
    }
    else
    {
        cout << "Deleted!"<< endl;
    }

    res = pthread_mutex_unlock(&t);
    cout << res << endl;
    pthread_exit(NULL);

    return 0;

}

Also at ideone

On one side as someone noted, the standard apparently says

Attempting to destroy a locked mutex or a mutex that is referenced (for example, while being used in a pthread_cond_timedwait() or pthread_cond_wait()) by another thread results in undefined behavior.

So one could assume that if it the same thread then it's OK.

It's odd because this sentence was changed in the older version it was not there and the line said only

It shall be safe to destroy an initialized mutex that is unlocked. Attempting to destroy a locked mutex results in undefined behavior.

So it's not that far fetched to think that this change was made for a reason, I'm just trying to be sure.

I tested the previously mentioned code on two different linux systems(ubuntu 13.10 and another debian 5774) and it fails and prints "Failed to delete: Device or resource busy # 1 1" , where on ideone's platform it succeeds.

Is ideones' behavior is just a specific case of undefined behavior? Or is there something wrong with the other cases?

Unfortunately I couldn't find a source that specifically addresses this issue.

回答1:

The quoted text:

Attempting to destroy a locked mutex or a mutex that is referenced (for example, while being used in a pthread_cond_timedwait() or pthread_cond_wait()) by another thread results in undefined behavior.

Should be interpreted with the "results in undefined behavior" clause distributed over the "or" conjunction. In other words:

Attempting to destroy a locked mutex results in undefined behavior.

and

Attempting to destroy a mutex that is referenced (for example, while being used in a pthread_cond_timedwait() or pthread_cond_wait()) by another thread results in undefined behavior.

The second version is significant, because when waiting on the condition variable, the associated mutex lock is released by the waiting thread.