Open Group的文档中指出:
NAME
pthread_rwlock_wrlock, pthread_rwlock_trywrlock - lock a read-write lock object for writing
...
The pthread_rwlock_wrlock() and pthread_rwlock_trywrlock() functions may fail if:
...
[EDEADLK]
The current thread already owns the read-write lock for writing or reading.
但是,当我运行以下代码时:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <pthread.h>
int main()
{
int error;
pthread_rwlock_t *mutex = (pthread_rwlock_t *)malloc(sizeof(pthread_rwlock_t));
if (mutex == NULL) {
perror("malloc");
abort();
}
pthread_rwlockattr_t attr;
error = pthread_rwlockattr_init(&attr);
if (error != 0)
{
fprintf(stderr, "%s:%d: pthread_rwlockattr_init failed: %s", __FILE__, __LINE__, strerror(error));
abort();
}
error = pthread_rwlock_init(mutex, &attr);
if (error != 0)
{
fprintf(stderr, "%s:%d: pthread_rwlock_init failed: %s", __FILE__, __LINE__, strerror(error));
abort();
}
error = pthread_rwlock_wrlock(mutex);
if (error != 0)
{
fprintf(stderr, "%s:%d: pthread_rwlock_wrlock failed: %s", __FILE__, __LINE__, strerror(error));
abort();
}
error = pthread_rwlock_rdlock(mutex);
if (error != 0)
{
fprintf(stderr, "%s:%d: pthread_rwlock_rdlock failed: %s", __FILE__, __LINE__, strerror(error));
abort();
}
return 0;
}
输出为:
main.c:53: pthread_rwlock_rdlock failed: Resource deadlock avoided
但是当我运行以下代码时:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <pthread.h>
int main()
{
int error;
pthread_rwlock_t *mutex = (pthread_rwlock_t *)malloc(sizeof(pthread_rwlock_t));
if (mutex == NULL) {
perror("malloc");
abort();
}
pthread_rwlockattr_t attr;
error = pthread_rwlockattr_init(&attr);
if (error != 0)
{
fprintf(stderr, "%s:%d: pthread_rwlockattr_init failed: %s", __FILE__, __LINE__, strerror(error));
abort();
}
error = pthread_rwlock_init(mutex, &attr);
if (error != 0)
{
fprintf(stderr, "%s:%d: pthread_rwlock_init failed: %s", __FILE__, __LINE__, strerror(error));
abort();
}
error = pthread_rwlock_rdlock(mutex);
if (error != 0)
{
fprintf(stderr, "%s:%d: pthread_rwlock_rdlock failed: %s", __FILE__, __LINE__, strerror(error));
abort();
}
error = pthread_rwlock_wrlock(mutex);
if (error != 0)
{
fprintf(stderr, "%s:%d: pthread_rwlock_wrlock failed: %s", __FILE__, __LINE__, strerror(error));
abort();
}
return 0;
}
在这种情况下,pthread_rwlock_wrlock
调用不会返回EDEADLK
而是被阻塞。
Open Group 的解释有误吗?EDEADLK
退货似乎更合理。这可能是什么问题?
我在 Linux 上使用 gcc 测试过,在安装了 WSL 的电脑上也测试过,还在 OnlineGDB 上测试过,但都无法正常工作。这似乎是一个常见的实现问题,而不是我的设置特有的问题。这种行为是故意的吗?