【问题标题】:is recursive mutex lock?是递归互斥锁吗?
【发布时间】:2014-05-26 18:10:25
【问题描述】:

我有一个关于mutex_lock 的问题。我的代码执行以下操作:

  1. RIL_startEventLoop通过pthread_mutex_lock(&s_startupMutex)锁定互斥锁;
  2. 调用线程eventLoop
  3. eventLoop 通过pthread_mutex_lock(&s_startupMutex) 锁定互斥锁;
  4. eventLoop 通过pthread_mutex_unlock(&s_startupMutex) 解锁互斥锁;
  5. RIL_startEventLoop 通过pthread_mutex_unlock(&s_startupMutex) 解锁互斥锁;

我的理解如下(如有错误请指正):

  1. 专门为此任务锁定互斥锁。如果互斥锁现在不可用,它会一直休眠直到它得到它。
  2. 互斥体必须稍后由获得它的同一任务释放。不允许递归锁定。

为什么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;
}

【问题讨论】:

    标签: c++ multithreading


    【解决方案1】:

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

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

    1. 释放互斥锁(它必须已经被获取)
    2. 暂停线程,直到发出条件信号
    3. 获取互斥锁

    【讨论】:

      猜你喜欢
      • 2010-09-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-29
      • 1970-01-01
      • 1970-01-01
      • 2018-06-10
      • 1970-01-01
      相关资源
      最近更新 更多