簡體   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