閒談pthread_cond_wait虛假喚醒

關於多線程下條件變量的作用這裏就不多講解了,這裏主要是針對條件變量操作時需要注意一個特性虛假喚醒,首先看一段代碼。

	task * _deal_task = NULL;
	//lock
	pthread_mutex_lock(&m_thread_mutex);				

	if(!m_task_queue.empty()) {
		//get task
		_deal_task = m_task_queue.front();
		m_task_queue.pop();
	}else{
		printf("produce_consumer condition wait\n");
		//deal spurious wakeup  - other singal affect this wait
		while(m_task_queue.empty()) {
			pthread_cond_wait(&m_thread_cond, &m_thread_mutex);
			//if program recv stop  break this while
			if(m_stop){
				break;
			}
		}
	}
	//unlock
	pthread_mutex_unlock(&m_thread_mutex);

上述代碼中可以發現在pthread_cond_wait上層有一層隊列循環檢測,目的就是爲了處理虛假喚醒,因爲我們用條件變量的時候等待cond信號,這個時候可能因爲某些特殊條件,我們的cond_wait會被意外喚醒,所以我們需要再次對資源進行檢測,確保是否達到所有觸發的條件,如果沒有滿足條件我們則繼續進行等待,如果滿足就認爲是正確的喚醒信號。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章