溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

C++多線程中的線程同步與互斥量實(shí)例分析

發(fā)布時間:2022-05-05 09:32:39 來源:億速云 閱讀:151 作者:zzz 欄目:開發(fā)技術(shù)

本篇內(nèi)容介紹了“C++多線程中的線程同步與互斥量實(shí)例分析”的有關(guān)知識,在實(shí)際案例的操作過程中,不少人都會遇到這樣的困境,接下來就讓小編帶領(lǐng)大家學(xué)習(xí)一下如何處理這些情況吧!希望大家仔細(xì)閱讀,能夠?qū)W有所成!

線程同步

/*
    使用多線程實(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資源。

C++多線程中的線程同步與互斥量實(shí)例分析

C++多線程中的線程同步與互斥量實(shí)例分析

原因: 休眠的時間,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)來確保同時僅有一個線程可以訪問某項共享資源??梢允褂没コ饬縼肀WC對任意共享資源的原子訪問。

互斥量有兩種狀態(tài):已鎖定(locked)和未鎖定(unlocked)。

任何時候,至多只有一個線程可以鎖定該互斥量。試圖對已經(jīng)鎖定的某一互斥量再次加鎖,將可能阻塞線程或者報錯失敗,具體取決于加鎖時使用的方法。

一旦線程鎖定互斥量,隨即成為該互斥量的所有者,只有所有者才能給互斥量解鎖。

一般情況下,對每一共享資源(可能由多個相關(guān)變量組成)會使用不同的互斥量,每一線程在訪問同一資源時將采用如下協(xié)議:

  • 針對共享資源鎖定互斥量

  • 訪問共享資源

  • 對互斥量解鎖

加鎖是在臨界區(qū)對共享數(shù)據(jù)操作;

如果多個線程試圖執(zhí)行這一塊代碼(一個臨界區(qū)),事實(shí)上只有一個線程能夠持有該互斥量(其他線程將遭到阻塞),即同時只有一個線程能夠進(jìn)入這段代碼區(qū)域,如下圖所示:

C++多線程中的線程同步與互斥量實(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語言的修飾符,被修飾的指針,不能由另外的一個指針進(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;
}

“C++多線程中的線程同步與互斥量實(shí)例分析”的內(nèi)容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業(yè)相關(guān)的知識可以關(guān)注億速云網(wǎng)站,小編將為大家輸出更多高質(zhì)量的實(shí)用文章!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

c++
AI