繁体   English   中英

当线程在已解锁的互斥锁上调用 pthread_mutex_unlock 时会发生什么

[英]What happens when a thread calls pthread_mutex_unlock on an already unlocked mutex

我知道这个问题听起来很熟悉,甚至可能是一个愚蠢的问题,但我无法找到解决方案。

所以我的问题基本上是,当parent_thread调用pthread_mutex_lock(&mutex)然后调用pthread_cond_wait(&condition, &mutex)释放互斥锁,然后child_thread调用pthread_mutex_lock(&mutex)后跟pthread_cond_signal(&condition)然后pthread_mutex_unlock(&mutex)会发生什么。 所以这意味着互斥锁已解锁,现在如果parent_thread尝试调用pthread_mutex_unlock(&mutex) ,它应该导致未定义的行为,对吧?

示例代码:

pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t c = PTHREAD_COND_INITIALIZER;

void thr_exit() {
  pthread_mutex_lock(&m);
  done = 1;
  pthread_cond_signal(&c);
  pthread_mutex_unlock(&m);
}

void *child(void *arg) {
  printf("child\n");
  thr_exit();
  return NULL;
} 
void thr_join() {
  pthread_mutex_lock(&m);
  while (done == 0)
  pthread_cond_wait(&c, &m); 
  pthread_mutex_unlock(&m); 
}

int main(int argc, char *argv[]) {
  printf("parent: begin\n"); 
  pthread_t p;
  pthread_create(&p, NULL, child, NULL);
  thr_join();
  printf("parent: end\n"); return 0;
}

对不起,我评论的时候才看你的标题。 只是为了确保我了解您的操作顺序,已发布答案的冗长版本:

家长来电:

pthread_mutex_lock(&m); // locks the mutex
pthread_cond_wait(&c, &m);  // releases the mutex

孩子打电话:

pthread_mutex_lock(&m);  // locks the mutex
pthread_cond_signal(&c); // does nothing to the mutex, it's still locked
// the parent thread has been signaled, but it is still blocked
// because it can't acquire the mutex.
// At this moment in time, the child still owns the mutex, so
// pthread_cond_wait cannot acquire it, thus the parent waits...

pthread_mutex_unlock(&m); // releases the mutex
// ok, the child released the mutex and the parent thread has been signaled.
// The mutex is available. pthread_cond_wait in the parent can
// acquire it and return.

家长来电:

// now that the mutex is unlocked, the parent can return from its
// pthread_cond_wait(&c, &m) call from above, which returns with the mutex
// locked. A successful call to pthread_cond_wait(..) returns with the
// mutex locked, so this can't successfully return until it acquires the
// mutex.
pthread_mutex_unlock(&m);  // releases the locked mutex, no UB

当然,这只是几个操作顺序之一。 我认为您的误解是pthread_cond_wait在获取互斥锁之前无法成功返回。 此时,它正确调用pthread_mutex_unlock(&m); 在锁定的互斥体上。

所以这意味着互斥锁已解锁

不, pthread_cond_wait返回并锁定互斥锁。

如果 parent_thread 尝试调用 pthread_mutex_unlock(&mutex)

pthread_cond_wait返回后,父级仅解锁互斥锁。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM