C++詳解多線程中的線程同步與互斥量
線程同步
/*
使用多線程實(shí)現(xiàn)買票的案例。
有3個窗口,一共是100張票。
*/
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
// 全局變量,所有的線程都共享這一份資源。
int tickets = 100;
void * sellticket(void * arg) {
// 賣票
while(tickets > 0) {
usleep(6000); //微秒
printf("%ld 正在賣第 %d 張門票\n", pthread_self(), tickets);
tickets--;
}
return NULL;
}
int main() {
// 創(chuàng)建3個子線程
pthread_t tid1, tid2, tid3;
pthread_create(&tid1, NULL, sellticket, NULL);
pthread_create(&tid2, NULL, sellticket, NULL);
pthread_create(&tid3, NULL, sellticket, NULL);
// 回收子線程的資源,默認(rèn)阻塞狀態(tài)
pthread_join(tid1, NULL);
pthread_join(tid2, NULL);
pthread_join(tid3, NULL);
// 設(shè)置線程分離。
// pthread_detach(tid1);
// pthread_detach(tid2);
// pthread_detach(tid3);
pthread_exit(NULL); // 退出主線程
return 0;
}運(yùn)行結(jié)果:
產(chǎn)生的問題:
- 每一張票都賣了好幾次;
- 賣了第0張票和-1張票,都是不對的;
三個線程搶cpu資源。


原因: 休眠的時間,3個進(jìn)程都進(jìn)去執(zhí)行了程序;多個進(jìn)程對共享資源同時處理,就會產(chǎn)生線程同步問題。
線程的主要優(yōu)勢: 通過全局變量來共享信息。不過,這種便捷的共享是有代價的:必須確保多個線程不會同時修改同一變量,或者某一線程不會讀取正在由其他線程修改的變量。
臨界區(qū):指訪問某一共享資源的代碼片段,并且這段代碼的執(zhí)行應(yīng)為原子操作,也就是同時訪問同一共享資源的其他線程不應(yīng)終端該片段的執(zhí)行。
線程同步: 即當(dāng)有一個線程在對內(nèi)存進(jìn)行操作時,其他線程都不可以對這個內(nèi)存地址進(jìn)行操作,直到該線程完成操作,其他線程才能對該內(nèi)存地址進(jìn)行操作,而其他線程則處于等待狀態(tài)。
線程同步會降低線程并發(fā)的效率,這是必須的。
互斥量
為避免線程更新共享變量時出現(xiàn)問題,可以使用互斥量(mutex)來確保同時僅有一個線程可以訪問某項(xiàng)共享資源??梢允褂没コ饬縼肀WC對任意共享資源的原子訪問。
互斥量有兩種狀態(tài):已鎖定(locked)和未鎖定(unlocked)。
任何時候,至多只有一個線程可以鎖定該互斥量。試圖對已經(jīng)鎖定的某一互斥量再次加鎖,將可能阻塞線程或者報錯失敗,具體取決于加鎖時使用的方法。
一旦線程鎖定互斥量,隨即成為該互斥量的所有者,只有所有者才能給互斥量解鎖。
一般情況下,對每一共享資源(可能由多個相關(guān)變量組成)會使用不同的互斥量,每一線程在訪問同一資源時將采用如下協(xié)議:
- 針對共享資源鎖定互斥量
- 訪問共享資源
- 對互斥量解鎖
加鎖是在臨界區(qū)對共享數(shù)據(jù)操作;
如果多個線程試圖執(zhí)行這一塊代碼(一個臨界區(qū)),事實(shí)上只有一個線程能夠持有該互斥量(其他線程將遭到阻塞),即同時只有一個線程能夠進(jìn)入這段代碼區(qū)域,如下圖所示:

/*
互斥量的類型 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語言的修飾符,被修飾的指針,不能由另外的一個指針進(jìn)行操作。
pthread_mutex_t *restrict mutex = xxx;
pthread_mutex_t * mutex1 = mutex; --不能這樣操作,有restrict關(guān)鍵詞
int pthread_mutex_destroy(pthread_mutex_t *mutex);
- 釋放互斥量的資源
int pthread_mutex_lock(pthread_mutex_t *mutex);
- 加鎖,阻塞的,如果有一個線程加鎖了,那么其他的線程只能阻塞等待
- 成功返回 0
int pthread_mutex_trylock(pthread_mutex_t *mutex);
- 嘗試加鎖,如果加鎖失敗,不會阻塞,會直接返回。
int pthread_mutex_unlock(pthread_mutex_t *mutex);
- 解鎖
*/
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
// 全局變量,所有的線程都共享這一份資源。
int tickets = 1000;
// 創(chuàng)建一個互斥量 --在全局區(qū)創(chuàng)建
pthread_mutex_t mutex;
void * sellticket(void * arg) {
// 賣票
while(1) {
// 加鎖
pthread_mutex_lock(&mutex);
if(tickets > 0) {
usleep(6000);
printf("%ld 正在賣第 %d 張門票\n", pthread_self(), tickets);
tickets--;
}else {
// 解鎖
pthread_mutex_unlock(&mutex);
break;
}
// 解鎖
pthread_mutex_unlock(&mutex);
}
return NULL;
}
int main() {
// 初始化互斥量
pthread_mutex_init(&mutex, NULL);
// 創(chuàng)建3個子線程
pthread_t tid1, tid2, tid3;
pthread_create(&tid1, NULL, sellticket, NULL);
pthread_create(&tid2, NULL, sellticket, NULL);
pthread_create(&tid3, NULL, sellticket, NULL);
// 回收子線程的資源,阻塞
pthread_join(tid1, NULL);
pthread_join(tid2, NULL);
pthread_join(tid3, NULL);
pthread_exit(NULL); // 退出主線程
// 釋放互斥量資源
pthread_mutex_destroy(&mutex);
return 0;
}到此這篇關(guān)于C++詳解多線程中的線程同步與互斥量的文章就介紹到這了,更多相關(guān)C++線程同步內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
C++詳細(xì)分析講解函數(shù)參數(shù)的擴(kuò)展
在C++中,定義函數(shù)時可以給形參指定一個默認(rèn)的值,這樣調(diào)用函數(shù)時如果沒有給這個形參賦值(沒有對應(yīng)的實(shí)參),那么就使用這個默認(rèn)的值。也就是說,調(diào)用函數(shù)時可以省略有默認(rèn)值的參數(shù)2022-04-04
C語言求Fibonacci斐波那契數(shù)列通項(xiàng)問題的解法總結(jié)
斐波那契數(shù)列相關(guān)問題是考研和ACM中常見的算法題目,這里特地為大家整理了C語言求Fibonacci斐波那契數(shù)列通項(xiàng)問題的解法總結(jié),需要的朋友可以參考下2016-06-06

