大话「线程同步」
文章目錄
- 初始線程同步
- 互斥量
- 互斥量相關(guān)操作函數(shù)
- 死鎖
- 讀寫(xiě)鎖
- 讀寫(xiě)鎖相關(guān)操作函數(shù)
- 生產(chǎn)者和消費(fèi)者模型
- 信號(hào)量
- 條件變量
初始線程同步
線程的主要優(yōu)勢(shì)在于,能夠通過(guò)全局變量來(lái)共享信息。不過(guò),這種便捷的共享是有代價(jià)的:必須確保多個(gè)線程不會(huì)同時(shí)修改同一變量,或者某一線程不會(huì)讀取正在由其他線程修改的變量。
臨界區(qū)是指訪問(wèn)某一共享資源的代碼片段,并且這段代碼的執(zhí)行應(yīng)為原子操作,也就是同時(shí)訪問(wèn)同一共享資源的其他線程不應(yīng)終端該片段的執(zhí)行。
線程同步即當(dāng)有一個(gè)線程在對(duì)內(nèi)存進(jìn)行操作時(shí),其他線程都不可以對(duì)這個(gè)內(nèi)存地址進(jìn)行操作,直到該線程完成操作,其他線程才能對(duì)該內(nèi)存地址進(jìn)行操作,而其他線程則處于等待狀態(tài)。
互斥量
為避免線程更新共享變量時(shí)出現(xiàn)問(wèn)題,可以使用互斥量(mutex 是 mutual exclusion的縮寫(xiě))來(lái)確保同時(shí)僅有一個(gè)線程可以訪問(wèn)某項(xiàng)共享資源。可以使用互斥量來(lái)保證對(duì)任意共享資源的原子訪問(wèn)。
互斥量有兩種狀態(tài):已鎖定(locked)和未鎖定(unlocked)。任何時(shí)候,至多只有一個(gè)線程可以鎖定該互斥量。試圖對(duì)已經(jīng)鎖定的某一互斥量再次加鎖,將可能阻塞線程或者報(bào)錯(cuò)失敗,具體取決于加鎖時(shí)使用的方法。
一旦線程鎖定互斥量,隨即成為該互斥量的所有者,只有所有者才能給互斥量解鎖。一般情況下,對(duì)每一共享資源(可能由多個(gè)相關(guān)變量組成)會(huì)使用不同的互斥量,每一線程在訪問(wèn)同一資源時(shí)將采用如下協(xié)議:
- 針對(duì)共享資源鎖定互斥量
- 訪問(wèn)共享資源
- 對(duì)互斥量解鎖
如果多個(gè)線程試圖執(zhí)行這一塊代碼(一個(gè)臨界區(qū)),事實(shí)上只有一個(gè)線程能夠持有該互斥量(其他線程將遭到阻塞),即同時(shí)只有一個(gè)線程能夠進(jìn)入這段代碼區(qū)域,如下圖所示:
互斥量相關(guān)操作函數(shù)
互斥量的類型 pthread_mutex_t int pthread_mutex_init(pthread_mutex_t *restrict mutex, const pthread_mutexattr_t *restrict attr);- 初始化互斥量- 參數(shù) :- mutex : 需要初始化的互斥量變量- attr : 互斥量相關(guān)的屬性,NULL- restrict : C語(yǔ)言的修飾符,被修飾的指針,不能由另外的一個(gè)指針進(jìn)行操作。pthread_mutex_t *restrict mutex = xxx;pthread_mutex_t * mutex1 = mutex;-返回值:成功則返回0, 出錯(cuò)則返回錯(cuò)誤編號(hào)int pthread_mutex_destroy(pthread_mutex_t *mutex);- 釋放互斥量的資源int pthread_mutex_lock(pthread_mutex_t *mutex);- 加鎖,阻塞的,如果有一個(gè)線程加鎖了,那么其他的線程只能阻塞等待-返回值:成功則返回0, 出錯(cuò)則返回錯(cuò)誤編號(hào)int pthread_mutex_unlock(pthread_mutex_t *mutex);- 解鎖-返回值:成功則返回0, 出錯(cuò)則返回錯(cuò)誤編號(hào)int pthread_mutex_trylock(pthread_mutex_t *mutex);- 嘗試加鎖,如果加鎖失敗,不會(huì)阻塞,會(huì)直接返回。- 案例
死鎖
有時(shí),一個(gè)線程需要同時(shí)訪問(wèn)兩個(gè)或更多不同的共享資源,而每個(gè)資源又都由不同的互斥量管理。當(dāng)超過(guò)一個(gè)線程加鎖同一組互斥量時(shí),就有可能發(fā)生死鎖。
兩個(gè)或兩個(gè)以上的進(jìn)程在執(zhí)行過(guò)程中,因爭(zhēng)奪共享資源而造成的一種互相等待的現(xiàn)象,若無(wú)外力作用,它們都將無(wú)法推進(jìn)下去。此時(shí)稱系統(tǒng)處于死鎖狀態(tài)或系統(tǒng)產(chǎn)生了死鎖。
死鎖的幾種場(chǎng)景:忘記釋放鎖、重復(fù)加鎖、多線程多鎖,搶占鎖資源。
讀寫(xiě)鎖
當(dāng)有一個(gè)線程已經(jīng)持有互斥鎖時(shí),互斥鎖將所有試圖進(jìn)入臨界區(qū)的線程都阻塞住。但是考慮一種情形,當(dāng)前持有互斥鎖的線程只是要讀訪問(wèn)共享資源,而同時(shí)有其它幾個(gè)線程也想讀取這個(gè)共享資源,但是由于互斥鎖的排它性,所有其它線程都無(wú)法獲取鎖,也就無(wú)法讀訪問(wèn)共享資源了,但是實(shí)際上多個(gè)線程同時(shí)讀訪問(wèn)共享資源并不會(huì)導(dǎo)致問(wèn)題。
在對(duì)數(shù)據(jù)的讀寫(xiě)操作中,更多的是讀操作,寫(xiě)操作較少,例如對(duì)數(shù)據(jù)庫(kù)數(shù)據(jù)的讀寫(xiě)應(yīng)用。
為了滿足當(dāng)前能夠允許多個(gè)讀出,但只允許一個(gè)寫(xiě)入的需求,線程提供了讀寫(xiě)鎖來(lái)實(shí)現(xiàn)。
讀寫(xiě)鎖的特點(diǎn):
- 如果有其它線程讀數(shù)據(jù),則允許其它線程執(zhí)行讀操作,但不允許寫(xiě)操作。
- 如果有其它線程寫(xiě)數(shù)據(jù),則其它線程都不允許讀、寫(xiě)操作。
- 寫(xiě)是獨(dú)占的,寫(xiě)的優(yōu)先級(jí)高。
讀寫(xiě)鎖相關(guān)操作函數(shù)
讀寫(xiě)鎖的類型 pthread_rwlock_t int pthread_rwlock_init(pthread_rwlock_t *restrict rwlock, const pthread_rwlockattr_t *restrict attr); int pthread_rwlock_destroy(pthread_rwlock_t *rwlock); int pthread_rwlock_rdlock(pthread_rwlock_t *rwlock); int pthread_rwlock_tryrdlock(pthread_rwlock_t *rwlock); int pthread_rwlock_wrlock(pthread_rwlock_t *rwlock); int pthread_rwlock_trywrlock(pthread_rwlock_t *rwlock); int pthread_rwlock_unlock(pthread_rwlock_t *rwlock);- 案例
生產(chǎn)者和消費(fèi)者模型
生產(chǎn)者消費(fèi)者模型(粗略的版本) #include <stdio.h> #include <pthread.h> #include <stdlib.h> #include <unistd.h>// 創(chuàng)建一個(gè)互斥量 pthread_mutex_t mutex;struct Node{int num;struct Node *next; };// 頭結(jié)點(diǎn) struct Node * head = NULL;void * producer(void * arg) {// 不斷的創(chuàng)建新的節(jié)點(diǎn),添加到鏈表中while(1) {pthread_mutex_lock(&mutex);struct Node * newNode = (struct Node *)malloc(sizeof(struct Node));newNode->next = head;head = newNode;newNode->num = rand() % 1000;printf("add node, num : %d, tid : %ld\n", newNode->num, pthread_self());pthread_mutex_unlock(&mutex);usleep(100);}return NULL; }void * customer(void * arg) {while(1) {pthread_mutex_lock(&mutex);// 保存頭結(jié)點(diǎn)的指針struct Node * tmp = head;// 判斷是否有數(shù)據(jù)if(head != NULL) {// 有數(shù)據(jù)head = head->next;printf("del node, num : %d, tid : %ld\n", tmp->num, pthread_self());free(tmp);pthread_mutex_unlock(&mutex);usleep(100);} else {// 沒(méi)有數(shù)據(jù)pthread_mutex_unlock(&mutex);}}return NULL; }int main() {pthread_mutex_init(&mutex, NULL);// 創(chuàng)建5個(gè)生產(chǎn)者線程,和5個(gè)消費(fèi)者線程pthread_t ptids[5], ctids[5];for(int i = 0; i < 5; i++) {pthread_create(&ptids[i], NULL, producer, NULL);pthread_create(&ctids[i], NULL, customer, NULL);}for(int i = 0; i < 5; i++) {pthread_detach(ptids[i]);pthread_detach(ctids[i]);}while(1) {sleep(10);}pthread_mutex_destroy(&mutex);pthread_exit(NULL);return 0; }信號(hào)量
信號(hào)量的類型 sem_t int sem_init(sem_t *sem, int pshared, unsigned int value);- 初始化信號(hào)量- 參數(shù):- sem : 信號(hào)量變量的地址- pshared : 0 用在線程間 ,非0 用在進(jìn)程間- value : 信號(hào)量中的值int sem_destroy(sem_t *sem);- 釋放資源int sem_wait(sem_t *sem);- 對(duì)信號(hào)量加鎖,調(diào)用一次對(duì)信號(hào)量的值-1,如果值為0,就阻塞int sem_trywait(sem_t *sem);int sem_timedwait(sem_t *sem, const struct timespec *abs_timeout); int sem_post(sem_t *sem);- 對(duì)信號(hào)量解鎖,調(diào)用一次對(duì)信號(hào)量的值+1int sem_getvalue(sem_t *sem, int *sval);sem_t psem; sem_t csem; init(psem, 0, 8); init(csem, 0, 0);producer() {sem_wait(&psem);sem_post(&csem) }customer() {sem_wait(&csem);sem_post(&psem) }- 案例
條件變量
互斥鎖有一個(gè)明顯到缺點(diǎn): 只有兩種狀態(tài),鎖定和非鎖定。
而條件變量則通過(guò)允許線程阻塞并等待另一個(gè)線程發(fā)送喚醒信號(hào)的方法彌補(bǔ)了互斥鎖的不足,它常和互斥鎖一起使用。
條件變量的類型 pthread_cond_t
等待,調(diào)用了該函數(shù),線程會(huì)阻塞:
? int pthread_cond_init(pthread_cond_t *restrict cond, const pthread_condattr_t *restrict attr);
? int pthread_cond_destroy(pthread_cond_t *cond);
? int pthread_cond_wait(pthread_cond_t *restrict cond, pthread_mutex_t *restrict mutex);
等待多長(zhǎng)時(shí)間,調(diào)用了這個(gè)函數(shù),線程會(huì)阻塞,直到指定的時(shí)間結(jié)束:
? int pthread_cond_timedwait(pthread_cond_t *restrict cond, pthread_mutex_t *restrict mutex, const struct timespec *restrict abstime);
喚醒一個(gè)或者多個(gè)等待的線程:
? int pthread_cond_signal(pthread_cond_t *cond);
喚醒所有的等待的線程:
? int pthread_cond_broadcast(pthread_cond_t *cond);
總結(jié)
- 上一篇: 基于osgEarth的空间态势三维场景视
- 下一篇: undefined运算