我对mutex_lock
有疑问。我的代码执行以下操作:
RIL_startEventLoop
按pthread_mutex_lock(&s_startupMutex)
; eventLoop
; eventLoop
按pthread_mutex_lock(&s_startupMutex)
; eventLoop
按pthread_mutex_unlock(&s_startupMutex)
; RIL_startEventLoop
按pthread_mutex_unlock(&s_startupMutex)
; 我的理解如下(如果错误,请纠正我):
为什么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;
}
答案 0 :(得分:0)
因为对pthread_cond_wait()的调用会释放互斥锁。
pthread_cond_wait()以原子方式执行此操作。