Linux下互斥量與條件變數詳解

來源:互聯網
上載者:User

1. 首先pthread_cond_wait 的定義是這樣的

The pthread_cond_wait() and pthread_cond_timedwait() functions are used to block on a condition variable. They are called with mutex locked by the calling thread or undefined behaviour will result.

These functions atomically release mutex and cause the calling thread to block on the condition variable cond;atomically here means "atomically with respect to access by anotherthread to the mutex and then the condition variable". That is, ifanother thread is able to acquire the mutex after the about-to-blockthread has released it, then a subsequent call topthread_cond_signal() or pthread_cond_broadcast() in that thread behaves as if it were issued after the about-to-block thread has blocked.

2. 由上解釋可以看出,pthread_cond_wait() 必須與pthread_mutex 配套使用。(wait的內部操作:一進入wait狀態就unclock,在wait結束前lock)

pthread_cond_wait()函數一進入wait狀態就會自動release mutex.

In Thread1:

pthread_mutex_lock(&m_mutex);  

pthread_cond_wait(&m_cond,&m_mutex);  

pthread_mutex_unlock(&m_mutex);  

In Thread2:

pthread_mutex_lock(&m_mutex);  

pthread_cond_signal(&m_cond);  

pthread_mutex_unlock(&m_mutex);  

為什麼要與pthread_mutex 一起使用呢?這是為了應對線程1在調用pthread_cond_wait()但線程1還沒有進入wait cond的狀態的時候,此時線程2調用了cond_singal 的情況。 如果不用mutex鎖的話,這個cond_singal就丟失了。加了鎖的情況是,線程2必須等到 mutex被釋放(也就是 pthread_cod_wait() 進入wait_cond狀態 並自動釋放mutex) 的時候才能調用cond_singal(前提:線程2也使用mutex)。

3. pthread_cond_wait() 一旦wait成功獲得cond 條件的時候會自動 lock mutex.

這就會出現另一個問題。這是因為

The pthread_cond_wait() and pthread_cond_timedwait() is a cancellation point.

In Thread3:

pthread_cancel(&m_thread);

pthread_join();

因為pthread_cond_wait() and pthread_cond_timedwait()   是線程退出點函數,因此在Thread3中

可以調用pthread_cancel()來退出線程1。那樣顯然線程1會在pthread_cond_wait(&m_cond,&m_mutex);    和pthread_mutex_unlock(&m_mutex); 之間退出,    pthread_cond_wait()函數返回後自動lock住了mutex,這個時候線程1退出(並沒有運行到pthread_mutex_unlock()),如果Thread2這個時候就再也得不到lock狀態了。

通常解決這個問題的辦法如下

void cleanup(void *arg)

{

  pthread_mutex_unlock(&mutex);

}

void* thread1(void* arg)

{

   pthread_cleanup_push(cleanup, NULL); // thread cleanup handler

   pthread_mutex_lock(&mutex);

  pthread_cond_wait(&cond, &mutex);

  pthread_mutex_unlock(&mutex);

  pthread_cleanup_pop(0);

}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.