其他分享
首页 > 其他分享> > c-销毁锁定的互斥锁时pthread_mutex_destroy的正确行为是什么

c-销毁锁定的互斥锁时pthread_mutex_destroy的正确行为是什么

作者:互联网

我写了以下最小示例:

#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;

}

也是在ideone

有人指出,一方面是the standard

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.

因此,可以假设,如果它是同一线程,那就可以了.

奇怪的是,这句话在较旧的版本中已更改,因此不存在,并且该行仅表示

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

因此,认为此更改是出于某种原因并不是一件容易的事,我只是想确定一下.

我在两个不同的linux系统(ubuntu 13.10和另一个debian 5774)上测试了前面提到的代码,它失败并显示“无法删除:设备或资源繁忙#1 1”,在ideone的平台上它成功了.

ideones的行为仅仅是未定义行为的一个特例吗?还是其他情况有问题?

不幸的是,我找不到专门解决此问题的资源.

解决方法:

引用文字:

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.

应该使用分布在“或”连接词上的“导致未定义行为的结果”子句来解释.换一种说法:

Attempting to destroy a locked mutex results in undefined behavior.

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.

第二个版本很重要,因为在等待条件变量时,等待的线程会释放关联的互斥锁.

标签:multithreading,pthreads,mutex,linux,c-4
来源: https://codeday.me/bug/20191029/1961590.html