是递归互斥锁吗?

时间:2014-05-26 09:53:53

标签: c++ multithreading

我对mutex_lock有疑问。我的代码执行以下操作:

  1. RIL_startEventLooppthread_mutex_lock(&s_startupMutex);
  2. 锁定互斥锁
  3. 调用线程eventLoop;
  4. eventLooppthread_mutex_lock(&s_startupMutex);
  5. 锁定互斥锁
  6. eventLooppthread_mutex_unlock(&s_startupMutex);
  7. 解锁互斥锁
  8. RIL_startEventLooppthread_mutex_unlock(&s_startupMutex);
  9. 解锁互斥锁

    我的理解如下(如果错误,请纠正我):

    1. 专门为此任务锁定互斥锁。如果互斥锁现在不可用,它将一直睡到它可以得到它。
    2. 以后必须通过获取它的相同任务释放互斥锁。不允许递归锁定。
    3. 为什么eventLoop可以锁定RIL_startEventLoop未发布的相同互斥锁?

      这两个函数在Ril.cpp中:

      RIL_startEventLoop(void) {
          int ret;
          pthread_attr_t attr;
      #ifdef MTK_RIL
          RIL_startRILProxys();
      #endif /* MTK_RIL */
          /* spin up eventLoop thread and wait for it to get started */
          s_started = 0;
          **pthread_mutex_lock(&s_startupMutex);**
      
          pthread_attr_init (&attr);
          pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
          ret = pthread_create(&s_tid_dispatch, &attr, **eventLoop**, NULL);
      
          while (s_started == 0) {
              pthread_cond_wait(&s_startupCond, &s_startupMutex);
          }
      
          **pthread_mutex_unlock(&s_startupMutex);**
      
          if (ret < 0) {
              LOGE("Failed to create dispatch thread errno:%d", errno);
              return;
          }
      }
      
      
      static void *
      **eventLoop(void *param)** {
          int ret;
          int filedes[2];
      
          ril_event_init();
      
          **pthread_mutex_lock(&s_startupMutex);**
      
          s_started = 1;
          pthread_cond_broadcast(&s_startupCond);
      
          **pthread_mutex_unlock(&s_startupMutex);**
      
          ret = pipe(filedes);
      
          if (ret < 0) {
              LOGE("Error in pipe() errno:%d", errno);
              return NULL;
          }
      
          s_fdWakeupRead = filedes[0];
          s_fdWakeupWrite = filedes[1];
      
          fcntl(s_fdWakeupRead, F_SETFL, O_NONBLOCK);
      
          ril_event_set (&s_wakeupfd_event, s_fdWakeupRead, true,
                         processWakeupCallback, NULL);
      
          rilEventAddWakeup (&s_wakeupfd_event);
      
          // Only returns on error
          ril_event_loop();
          LOGE ("error in event_loop_base errno:%d", errno);
      
          return NULL;
      }
      

1 个答案:

答案 0 :(得分:0)

因为对pthread_cond_wait()的调用会释放互斥锁。

pthread_cond_wait()以原子方式执行此操作。

  1. 释放互斥锁(必须已获取)
  2. 暂停线程,直到发出状态信号
  3. 获取互斥锁