则行为是否未定义

则行为是否未定义

本文介绍了如果您解锁已经解锁的互斥锁,则行为是否未定义?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果解锁已经解锁的互斥锁,则该行为是不安全的,安全的还是未定义的?

If you unlock an already unlocked mutex, is the behavior unsafe, safe, or undefined?

该问题的目的与以下代码有关,我不知道在if块内还是在if块外解锁互斥锁是否更好.

The purpose of the question is related to the following code, where I don't know if it would be better to unlock the mutexes within the if block, or just outside the if block.

    // This chunk of code makes dual locking semi-autonomous.
    int c_lckd = 0, q_lckd = 0;
    if (pthread_mutex_trylock(&crunch_mutex) == 0) c_lckd = 1;
    if (pthread_mutex_trylock(&queue_mutex) == 0) q_lckd = 1;
    if (q_lckd && !c_lckd) { QUEUE_UNLOCK; q_lckd = 0; }
    else if (c_lckd && !q_lckd) { CRUNCH_UNLOCK; c_lckd = 0; }

    if (c_lckd && q_lckd) {
      printf("cr = %d, max = %d, cnt = %d\n",
        crunching, max_crunching, queue_count(conn_queue));
      if (crunching < max_crunching && queue_count(conn_queue)) {
        pthread_t tid =
          pthread_create(
            &tid,
            NULL,
            crunch_conn,
            (void *)queue_dequeue(conn_queue)
          );
        crunching++;
      }
      CRUNCH_UNLOCK QUEUE_UNLOCK
    }

谢谢,钦茨

推荐答案

对于pthread,它将导致不确定的行为.在 pthread_mutex_unlock 的手册页中:

For pthreads it will result in undefined behaviour. From the man page for pthread_mutex_unlock:

其他互斥锁将具有自己的行为.正如其他人所说,最好阅读所用互斥锁的手册.

Other mutexes will have their own behviour. As others have stated, it's best to read the manual for whichever mutex you're using.

这篇关于如果您解锁已经解锁的互斥锁,则行为是否未定义?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 01:49