gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 21:00:04 24 4
gpt4 key购买 nike

我写了以下最小示例:

#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)上测试了前面提到的代码,但它失败了并打印“Failed to delete: Device or resource busy # 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.

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

关于c++ - 销毁锁定的互斥锁时 pthread_mutex_destroy 的正确行为是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23118606/

24 4 0