互斥量就是一把鎖,在訪問資料時能保證同一時間內只有一個線程訪問資料,在訪問完以後再釋放互斥量上的鎖。
條件變數是利用線程間共用的全域變數進行同步的一種機制,主要包括兩個動作:一個線程等待"條件變數的條件成立"而掛起;另一個線程使"條件成立"(給出條件成立訊號)。為了防止競爭,條件變數的使用總是和一個互斥鎖結合在一起。
條件變數應該和互斥量配合使用,以避免出現條件競爭,一個線程預備等待一個條件變數,當它在真正進入等待之前,另一個線程恰好觸發了該條件.
條件變數採用的資料類型是pthread_cond_t,在使用之前必須要進行初始化,與互斥鎖類型,也包括兩種方式.
靜態初始化:可以把常量PTHREAD_COND_INITIALIZER賦給靜態分配的條件變數;
動態初始化:在申請記憶體(malloc)後,通過pthread_cond_init進行初始化.注意在釋放記憶體前需要調用pthread_cond_destory.動態方式調用pthread_cond_init()函數,API定義如下:
int pthread_cond_init(pthread_cond_t *cond, pthread_condattr_t *cond_attr)
結構pthread_condattr_t是條件變數的屬性結構,和互斥鎖一樣我們可以用它來設定條件變數是進程內可用還是進程間可用,預設值是PTHREAD_ PROCESS_PRIVATE,即此條件變數被同一進程內的各個線程使用;如果選擇為PTHREAD_PROCESS_SHARED則為多個進程間各線程公用。注意初始化條件變數只有未被使用時才能重新初始化或被釋放。
int pthread_cond_wait(pthread_cond_t *cond, pthread_mutex_t *mutex)
int pthread_cond_timedwait(pthread_cond_t *cond, pthread_mutex_t *mutex, const struct timespec *abstime)
等待條件有兩種方式:無條件等待pthread_cond_wait()和計時等待pthread_cond_timedwait(),其中計時等待方式如果在給定時刻前條件沒有滿足,則返回ETIMEOUT,結束等待,其中abstime以與time()系統調用相同意義的絕對時間形式出現,0表示格林尼治時間1970年1月1日0時0分0秒。
無論哪種等待方式,都必須和一個互斥鎖配合,以防止多個線程同時請求pthread_cond_wait()(或pthread_cond_timedwait(),下同)的競爭條件(Race Condition)。mutex互斥鎖必須是普通鎖(PTHREAD_MUTEX_TIMED_NP)或者適應鎖(PTHREAD_MUTEX_ADAPTIVE_NP),且在調用pthread_cond_wait()前必須由本線程加鎖(pthread_mutex_lock()),而在更新條件等待隊列以前,mutex保持鎖定狀態,並線上程掛起進入等待前解鎖。在條件滿足從而離開pthread_cond_wait()之前,mutex將被重新加鎖,以與進入pthread_cond_wait()前的加鎖動作對應。
激發條件有兩種形式,pthread_cond_signal()啟用一個等待該條件的線程,存在多個等待線程時按入隊順序啟用其中一個;而pthread_cond_broadcast()則啟用所有等待線程。
#include <pthread.h>#include <unistd.h>#include <stdio.h>#include <stdlib.h>static pthread_mutex_t mtx = PTHREAD_MUTEX_INITIALIZER;static pthread_cond_t cond = PTHREAD_COND_INITIALIZER;struct node {int n_number;struct node *n_next;} *head = NULL;/*[thread_func]*/static void cleanup_handler(void *arg){ printf("Cleanup handler of second thread.\n"); free(arg); (void)pthread_mutex_unlock(&mtx);}static void *thread_func(void *arg){ struct node *p = NULL; pthread_cleanup_push(cleanup_handler, p); while (1) { pthread_mutex_lock(&mtx); while (head == NULL) { pthread_cond_wait(&cond, &mtx); } p = head; head = head->n_next; printf("Got %d from front of queue\n", p->n_number); free(p); pthread_mutex_unlock(&mtx); } pthread_cleanup_pop(0); return 0;}int main(void){ pthread_t tid; int i; struct node *p; pthread_create(&tid, NULL, thread_func, NULL); /*[tx6-main]*/ for (i = 0; i < 5; i++) { p = malloc(sizeof(struct node)); p->n_number = i; pthread_mutex_lock(&mtx); p->n_next = head; head = p; pthread_cond_signal(&cond); pthread_mutex_unlock(&mtx); sleep(1); } printf("thread 1 wanna end the line.So cancel thread 2.\n"); pthread_cancel(tid); pthread_join(tid, NULL); printf("All done -- exiting\n"); return 0;}