c - 第二个线程上的 PTHREAD_MUTEX_RECURSIVE block

标签 c pthreads

我对 PTHREAD_MUTEX_RECURSIVE 有以下问题:当互斥体被另一个线程锁定时它会阻塞;

pthread_mutex_t m;
pthread_mutexattr_t ma;

void* exec_th(void* arg) {
    printf("THREAD %p before LOCK\n", pthread_self());

    //second mutex lock
    pthread_mutex_lock(&m);
    printf("THREAD %p after LOCK\n", pthread_self());

    pthread_mutex_unlock(&m);
    printf("THREAD %p after UNLOCK\n", pthread_self());

    return (void*)0;
}

int main() {
    pthread_mutexattr_init(&ma);
    pthread_mutexattr_settype(&ma, PTHREAD_MUTEX_RECURSIVE);
    pthread_mutex_init(&m, &ma);

    // first mutex lock
    pthread_mutex_lock(&m);

    // create a thread that will call the same mutex
    pthread_t t;
    pthread_create(&t, NULL, exec_th, NULL);

    sleep(1); //just to see the console

    pthread_mutex_unlock(&m);
}

OpenGroup 指出:

A thread attempting to relock this mutex without first unlocking it will succeed in locking the mutex. The relocking deadlock which can occur with mutexes of type PTHREAD_MUTEX_NORMAL cannot occur with this type of mutex

不过,上面的代码为 PTHREAD_MUTEX_RECURSIVE 和 PTHREAD_MUTEX_NORMAL 生成了相同的行为:

  • 只有 在 LOCK 之前 在 main() 中的 sleep() 之前打印;
  • 线程在 main() 释放后锁定互斥锁;

非常感谢任何帮助,谢谢。

最佳答案

it blocks when the mutex is locked from another thread

如果互斥量是递归的,并且调用 pthread_mutex_lock 的线程已经持有该互斥量,那么它才会立即返回。在您的情况下,main 线程锁定了互斥锁,而另一个线程试图获取该互斥锁,但由于它由另一个线程持有而被阻止。这是正常行为。

如果任何线程可以解锁其他线程持有的任何(递归)互斥锁,那么递归互斥锁将毫无用处!

参见 POSIX也有文档。

关于c - 第二个线程上的 PTHREAD_MUTEX_RECURSIVE block ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50138578/

相关文章:

c - 各种平台上的指针地址跨度

指向字节结构成员的 C 字指针

c - 不同线程中的全局变体是否意味着不同的变体?

c++ - 不可预测的线程行为

c - 线程中的 sleep() 导致 main 也进入休眠状态

c++ - 乘以定义的符号: mysqlclient, pthread-win32

c++ - 编译器之间的浮点不匹配(Visual Studio 2010 和 GCC)

c - realloc 似乎没有扩大阵列

c++ - 在生产者继续之前等待所有异步消费者完成

c - C 中 pthread 的竞争条件