日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網(wǎng)站首頁 編程語言 正文

C++詳解多線程中的線程同步與互斥量_C 語言

作者:liufeng2023 ? 更新時間: 2022-06-28 編程語言

線程同步

/*
    使用多線程實現(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);
    // 回收子線程的資源,默認阻塞狀態(tài)
    pthread_join(tid1, NULL);
    pthread_join(tid2, NULL);
    pthread_join(tid3, NULL);
    // 設置線程分離。
    // pthread_detach(tid1);
    // pthread_detach(tid2);
    // pthread_detach(tid3);
    pthread_exit(NULL); // 退出主線程
    return 0;
}

運行結果:

產(chǎn)生的問題:

  • 每一張票都賣了好幾次;
  • 賣了第0張票和-1張票,都是不對的;

三個線程搶cpu資源。

原因: 休眠的時間,3個進程都進去執(zhí)行了程序;多個進程對共享資源同時處理,就會產(chǎn)生線程同步問題。

線程的主要優(yōu)勢: 通過全局變量來共享信息。不過,這種便捷的共享是有代價的:必須確保多個線程不會同時修改同一變量,或者某一線程不會讀取正在由其他線程修改的變量。

臨界區(qū):指訪問某一共享資源的代碼片段,并且這段代碼的執(zhí)行應為原子操作,也就是同時訪問同一共享資源的其他線程不應終端該片段的執(zhí)行。

線程同步: 即當有一個線程在對內存進行操作時,其他線程都不可以對這個內存地址進行操作,直到該線程完成操作,其他線程才能對該內存地址進行操作,而其他線程則處于等待狀態(tài)。

線程同步會降低線程并發(fā)的效率,這是必須的。

互斥量

為避免線程更新共享變量時出現(xiàn)問題,可以使用互斥量(mutex)來確保同時僅有一個線程可以訪問某項共享資源。可以使用互斥量來保證對任意共享資源的原子訪問。

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

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

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

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

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

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

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

/*
    互斥量的類型 pthread_mutex_t
    int pthread_mutex_init(pthread_mutex_t *restrict mutex, const pthread_mutexattr_t *restrict attr);
        - 初始化互斥量
        - 參數(shù) :
            - mutex : 需要初始化的互斥量變量
            - attr : 互斥量相關的屬性,NULL
        - restrict : C語言的修飾符,被修飾的指針,不能由另外的一個指針進行操作。
            pthread_mutex_t *restrict mutex = xxx;
            pthread_mutex_t * mutex1 = mutex;	--不能這樣操作,有restrict關鍵詞
    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;
}

原文鏈接:https://blog.csdn.net/Edward_LF/article/details/124510131

欄目分類
最近更新