(1)條件變量
? ? ? ? ? ? ? ?條件變量本身不是鎖,但它可以造成線程阻塞,通常與互斥鎖配合使用。
(2)條件鎖相關函數
? ? ? ? ? ? ? pthread_cond_t類型,用于定義條件變量
? ? ? ? ?1)初始化一個條件變量:pthread_cond_init
? ? ? ? ? ? ? ? ?int pthread_cond_init(pthread_cond_t *restrict cond,const pthread_condattr_t *restrict attr);
? ? ? ? ? ? ? ?參數2:條件變量的屬性,傳NULL即可,為默認值
? ? ? ? ? ? ? ?可采用靜態初始化:pthread _cond_t cond=PTHREAD_COND_INITIALIZER;
? ? ? ? ?2)銷毀一個條件變量:pthread_cond_destroy
? ? ? ? ? ? ? ? int pthread_cond_destroy(pthread_cond_t *cond);
? ? ? ? ?3)阻塞等待條件變量:pthread_cond_wait(配合互斥鎖使用)
? ? ? ? ? ? ? ? int pthread_cond_wait(pthread_cond_t *restrict cond,pthread_mutex_t *restrict mutex);
? ? ? ? ? ? ? ? 函數作用:?
? ? ? ? ? ? ? ? ? ? ? ? ? ?1>阻塞等待條件變量cond滿足。
? ? ? ? ? ? ? ? ? ? ? ? ? ?2>釋放已掌握的互斥鎖(解鎖互斥量)相當于pthread_mutex_unlock(&mutex);?
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?第1,2步為一個原子操作
? ? ? ? ? ? ? ? ? ? ? ? ? 3>當被喚醒,pthread_cond_wait函數返回,解除阻塞并重新獲得互斥鎖pthread_mutex_lock(&mutex)
? ? ? ?? 4)限時等待一個條件變量(以絕對時間等待):pthread_cond_timewait
? ? ? ? ? ? ? ? int pthread_cond_timewait(pthread_cond_t *restrict cond,pthread_mutex_t *restrict mutex,condt struct timespec*restrcit abstime);
? ? ? ? ? ? ?struct timespec{
? ? ? ? ? ? ? ? ? ? ? ? ? time_t tv_sec;//秒
? ? ? ? ? ? ? ? ? ? ? ? ?long? ? tv_nsec;//納秒
? ? ? ? ? ? ? };
?abstime;絕對時間,通過time(NULL)函數獲取;
? ? ? ? ? 5)喚醒至少一個阻塞在條件變量上的線程:pthread_cond_signal
? ? ? ? ? ? ? ?int pthread_cond_signal(pthread_cond_t *cond);
? ? ? ? 6)喚醒全部阻塞在條件變量上的線程:pthread_cond_broadcast(pthread_cond_t? *cond);
(3)線程同步之生產者消費者變量模型
? ? ? ? ? 假定有兩個線程,一個模擬生產者行為,一個模擬消費者行為。兩個線程同時操作一個共享資源(匯聚),生產者生產產品,消費者消費產品。
? ? ? ??
? ? ? ?
? ? ? ? ? ? ? ??
?