我知道這個問題聽起來很熟悉,甚至可能是一個愚蠢的問題,但我無法找到解決方案。
所以我的問題基本上是,當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_threadpthread_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;
}
uj5u.com熱心網友回復:
對不起,我評論的時候才看你的標題。只是為了確保我了解您的操作順序,已發布答案的冗長版本:
家長來電:
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);了一個鎖定的互斥體。
uj5u.com熱心網友回復:
所以這意味著互斥鎖已解鎖
不,pthread_cond_wait回傳并鎖定互斥鎖。
如果 parent_thread 嘗試呼叫 pthread_mutex_unlock(&mutex)
pthread_cond_wait父母只是在回傳后解鎖互斥鎖。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/477680.html
上一篇:memccpy如何處理大整數值?
下一篇:在C中當前行程的堆中搜索和編輯值
