最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Linux中實(shí)現(xiàn)線程同步的6種方法

 更新時(shí)間:2024年11月08日 09:34:37   作者:morris131  
本文詳細(xì)介紹了Linux下線程同步的多種方法,包括互斥鎖、自旋鎖、信號(hào)量以及它們的使用示例,通過(guò)這些同步機(jī)制,可以解決線程安全問(wèn)題,防止資源競(jìng)爭(zhēng)導(dǎo)致的錯(cuò)誤,示例代碼展示了如何在多線程環(huán)境中正確地管理共享資源,確保線程安全,需要的朋友可以參考下

linux線程同步的方法

下面是一個(gè)線程不安全的例子:

#include<stdio.h>
#include<pthread.h>

int ticket_num=10000000;

void *sell_ticket(void *arg) {
    while(ticket_num>0) {
	ticket_num--;
    }
}

int main() {
    pthread_t t1,t2,t3;
    pthread_create(&t1, NULL, &sell_ticket, NULL);
    pthread_create(&t2, NULL, &sell_ticket, NULL);
    pthread_create(&t3, NULL, &sell_ticket, NULL);
    pthread_join(t1, NULL);
    pthread_join(t2, NULL);
    pthread_join(t3, NULL);
    printf("ticket_num=%d\n", ticket_num);
    return 0;
}

運(yùn)行結(jié)果如下:

# gcc no_lock_demo.c -o no_lock_demo.out -pthread
# ./no_lock_demo.out 
ticket_num=-2

最后運(yùn)行的結(jié)果不是固定的,有可能是0、-1,如果有這個(gè)ticket_num變量代表是庫(kù)存的話,那么就會(huì)出現(xiàn)庫(kù)存為負(fù)數(shù)的情況,所以需要引入線程同步來(lái)保證線程安全。

Linux下提供了多種方式來(lái)處理線程同步,最常用的是互斥鎖、自旋鎖、信號(hào)量。

互斥鎖

互斥鎖本質(zhì)就是一個(gè)特殊的全局變量,擁有l(wèi)ock和unlock兩種狀態(tài),unlock的互斥鎖可以由某個(gè)線程獲得,當(dāng)互斥鎖由某個(gè)線程持有后,這個(gè)互斥鎖會(huì)鎖上變成lock狀態(tài),此后只有該線程有權(quán)力打開該鎖,其他想要獲得該互斥鎖的線程都會(huì)阻塞,直到互斥鎖被解鎖。

互斥鎖的類型:

  • 普通鎖(PTHREAD_MUTEX_NORMAL):互斥鎖默認(rèn)類型。當(dāng)一個(gè)線程對(duì)一個(gè)普通鎖加鎖以后,其余請(qǐng)求該鎖的線程將形成一個(gè) 等待隊(duì)列,并在該鎖解鎖后按照優(yōu)先級(jí)獲得它,這種鎖類型保證了資源分配的公平性。一個(gè) 線程如果對(duì)一個(gè)已經(jīng)加鎖的普通鎖再次加鎖,將引發(fā)死鎖;對(duì)一個(gè)已經(jīng)被其他線程加鎖的普 通鎖解鎖,或者對(duì)一個(gè)已經(jīng)解鎖的普通鎖再次解鎖,將導(dǎo)致不可預(yù)期的后果。

  • 檢錯(cuò)鎖(PTHREAD_MUTEX_ERRORCHECK):一個(gè)線程如果對(duì)一個(gè)已經(jīng)加鎖的檢錯(cuò)鎖再次加鎖,則加鎖操作返回EDEADLK;對(duì)一個(gè)已 經(jīng)被其他線程加鎖的檢錯(cuò)鎖解鎖或者對(duì)一個(gè)已經(jīng)解鎖的檢錯(cuò)鎖再次解鎖,則解鎖操作返回 EPERM。

  • 嵌套鎖(PTHREAD_MUTEX_RECURSIVE):該鎖允許一個(gè)線程在釋放鎖之前多次對(duì)它加鎖而不發(fā)生死鎖;其他線程要獲得這個(gè)鎖,則當(dāng)前鎖的擁有者必須執(zhí)行多次解鎖操作;對(duì)一個(gè)已經(jīng)被其他線程加鎖的嵌套鎖解鎖,或者對(duì)一個(gè)已經(jīng)解鎖的嵌套鎖再次解鎖,則解鎖操作返回EPERM。

  • 默認(rèn)鎖(PTHREAD_MUTEX_ DEFAULT):一個(gè)線程如果對(duì)一個(gè)已經(jīng)加鎖的默認(rèn)鎖再次加鎖,或者雖一個(gè)已經(jīng)被其他線程加鎖的默 認(rèn)鎖解鎖,或者對(duì)一個(gè)解鎖的默認(rèn)鎖解鎖,將導(dǎo)致不可預(yù)期的后果;這種鎖實(shí)現(xiàn)的時(shí)候可能 被映射成上述三種鎖之一。

相關(guān)方法:

// 靜態(tài)方式創(chuàng)建互斥鎖
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER? 

// 動(dòng)態(tài)方式創(chuàng)建互斥鎖,其中參數(shù)mutexattr用于指定互斥鎖的類型,具體類型見(jiàn)上面四種,如果為NULL,就是普通鎖。
int pthread_mutex_init (pthread_mutex_t* mutex,const pthread_mutexattr_t* mutexattr);

int pthread_mutex_lock(pthread_mutex_t *mutex); // 加鎖,阻塞
int pthread_mutex_trylock(pthread_mutex_t *mutex); // 嘗試加鎖,非阻塞
int pthread_mutex_unlock(pthread_mutex_t *mutex); // 解鎖

例子:

#include<stdio.h>
#include<pthread.h>

int ticket_num=10000000;

pthread_mutex_t mutex=PTHREAD_MUTEX_INITIALIZER;

void *sell_ticket(void *arg) {
    while(ticket_num>0) {
	pthread_mutex_lock(&mutex);
	if(ticket_num>0) {
	    ticket_num--;
	}
	pthread_mutex_unlock(&mutex);
    }
}

int main() {
    pthread_t t1,t2,t3;
    pthread_create(&t1, NULL, &sell_ticket, NULL);
    pthread_create(&t2, NULL, &sell_ticket, NULL);
    pthread_create(&t3, NULL, &sell_ticket, NULL);
    pthread_join(t1, NULL);
    pthread_join(t2, NULL);
    pthread_join(t3, NULL);
    printf("ticket_num=%d\n", ticket_num);
    return 0;
}

自旋鎖

自旋鎖顧名思義就是一個(gè)死循環(huán),不停的輪詢,當(dāng)一個(gè)線程未獲得自旋鎖時(shí),不會(huì)像互斥鎖一樣進(jìn)入阻塞休眠狀態(tài),而是不停的輪詢獲取鎖,如果自旋鎖能夠很快被釋放,那么性能就會(huì)很高,如果自旋鎖長(zhǎng)時(shí)間不能夠被釋放,甚至里面還有大量的IO阻塞,就會(huì)導(dǎo)致其他獲取鎖的線程一直空輪詢,導(dǎo)致CPU使用率達(dá)到100%,特別CPU時(shí)間。

相關(guān)方法:

int pthread_spin_init(pthread_spinlock_t *lock, int pshared)? // 創(chuàng)建自旋鎖

int pthread_spin_lock(pthread_spinlock_t *lock)? // 加鎖,阻塞
int pthread_spin_trylock(pthread_spinlock_t *lock)? // 嘗試加鎖,非阻塞
int pthread_spin_unlock(pthread_spinlock_t *lock)? // 解鎖

例子:

#include<stdio.h>
#include<pthread.h>

int ticket_num=10000000;

pthread_spinlock_t spinlock;

void *sell_ticket(void *arg) {
    while(ticket_num>0) {
	pthread_spin_lock(&spinlock);
	if(ticket_num>0) {
	    ticket_num--;
	}
	pthread_spin_unlock(&spinlock);
    }
}

int main() {
    pthread_spin_init(&spinlock, 0);
    pthread_t t1,t2,t3;
    pthread_create(&t1, NULL, &sell_ticket, NULL);
    pthread_create(&t2, NULL, &sell_ticket, NULL);
    pthread_create(&t3, NULL, &sell_ticket, NULL);
    pthread_join(t1, NULL);
    pthread_join(t2, NULL);
    pthread_join(t3, NULL);
    printf("ticket_num=%d\n", ticket_num);
    return 0;
}

信號(hào)量

信號(hào)量是一個(gè)計(jì)數(shù)器,用于控制訪問(wèn)有限共享資源的線程數(shù)。

相關(guān)方法:

// 創(chuàng)建信號(hào)量
// pshared:一般取0,表示調(diào)用進(jìn)程的信號(hào)量。非0表示該信號(hào)量可以共享內(nèi)存的方式,為多個(gè)進(jìn)程所共享(Linux暫不支持)。
// value:信號(hào)量的初始值,可以并發(fā)訪問(wèn)的線程數(shù)。
int sem_init (sem_t* sem, int pshared, unsigned int value);

int sem_wait (sem_t* sem); // 信號(hào)量減1,信號(hào)量為0時(shí)就會(huì)阻塞

int sem_trywait (sem_t* sem); // 信號(hào)量減1,信號(hào)量為0時(shí)返回-1,不阻塞

int sem_timedwait (sem_t* sem, const struct timespec* abs_timeout); // 信號(hào)量減1,信號(hào)量為0時(shí)阻塞,直到abs_timeout超時(shí)返回-1

int sem_post (sem_t* sem); // 信號(hào)量加1

例子:

#include<stdio.h>
#include<pthread.h>
#include <semaphore.h>

int ticket_num=10000000;

sem_t sem;

void *sell_ticket(void *arg) {
    while(ticket_num>0) {
	sem_wait(&sem);
	if(ticket_num>0) {
	    ticket_num--;
	}
	sem_post(&sem);
    }
}

int main() {
    sem_init(&sem, 0, 1); // value=1表示最多1個(gè)線程同時(shí)訪問(wèn)共享資源,與互斥量等價(jià)
    pthread_t t1,t2,t3;
    pthread_create(&t1, NULL, &sell_ticket, NULL);
    pthread_create(&t2, NULL, &sell_ticket, NULL);
    pthread_create(&t3, NULL, &sell_ticket, NULL);
    pthread_join(t1, NULL);
    pthread_join(t2, NULL);
    pthread_join(t3, NULL);
    printf("ticket_num=%d\n", ticket_num);
    return 0;
}

條件變量

條件變量可以讓調(diào)用線程在滿足特定條件的情況下運(yùn)行,不滿足條件時(shí)阻塞等待被喚醒,必須與互斥鎖搭配使用。

條件變量常用于生產(chǎn)者與消費(fèi)者模型。

相關(guān)方法:

pthread_cond_t cond=PTHREAD_COND_INITIALIZER; // 創(chuàng)建條件變量,一個(gè)互斥鎖可以對(duì)應(yīng)多個(gè)條件變量

int pthread_cond_wait (pthread_cond_t* cond,pthread_mutex_t* mutex); // 阻塞等待條件滿足,同時(shí)釋放互斥鎖mutex

int pthread_cond_timedwait (pthread_cond_t* cond,
    pthread_mutex_t* mutex,
    const struct timespec* abstime); // 帶超時(shí)的阻塞等待條件滿足,同時(shí)釋放互斥鎖mutex

// 從條件變量cond中喚出一個(gè)線程,令其重新獲得原先的互斥鎖
// 被喚出的線程此刻將從pthread_cond_wait函數(shù)中返回,但如果該線程無(wú)法獲得原先的鎖,則會(huì)繼續(xù)阻塞在加鎖上。
int pthread_cond_signal (pthread_cond_t* cond);

// 從條件變量cond中喚出所有線程
int pthread_cond_broadcast (pthread_cond_t* cond);

例子:

#include<stdio.h>
#include<pthread.h>

int max_buffer=10;
int count=0;

pthread_mutex_t mutex=PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t notempty=PTHREAD_COND_INITIALIZER;
pthread_cond_t notfull=PTHREAD_COND_INITIALIZER;

void *produce(void *args) {
    while(1) {
        pthread_mutex_lock(&mutex);
        while(count == max_buffer) {
            printf("buffer is full, wait...\n");
            pthread_cond_wait(&notfull, &mutex);
        }
        printf("produce ...\n");
        count++;
        sleep(1);
        pthread_cond_signal(&notempty);
        pthread_mutex_unlock(&mutex);
    }

}

void *consumer(void *args) {
    while(1) {
        pthread_mutex_lock(&mutex);
        while(count == 0) {
            printf("buffer is empty, wait...\n");
            pthread_cond_wait(&notempty, &mutex);
        }
        printf("consumer ...\n");
        count--;
        sleep(1);
        pthread_cond_signal(&notfull);
        pthread_mutex_unlock(&mutex);
    }

}

int main() {
    pthread_t t1,t2,t3,t4;
    pthread_create(&t1, NULL, &produce, NULL);
    pthread_create(&t2, NULL, &produce, NULL);

    pthread_create(&t3, NULL, &consumer, NULL);
    pthread_create(&t4, NULL, &consumer, NULL);

    pthread_join(t1, NULL);
    return 0;
}

讀寫鎖

讀寫鎖可以有三種狀態(tài):讀模式下加鎖狀態(tài),寫模式下加鎖狀態(tài),不加鎖狀態(tài)。一次只有一個(gè)線程可以占有寫模式的讀寫鎖,但是多個(gè)線程可以同時(shí)占有讀模式的讀寫鎖。讀寫鎖也叫做共享-獨(dú)占鎖,當(dāng)讀寫鎖以讀模式鎖住時(shí),它是以共享模式鎖住的,當(dāng)它以寫模式鎖住時(shí),它是以獨(dú)占模式鎖住的,讀讀共享,讀寫互斥。

相關(guān)方法:

// 創(chuàng)建讀寫鎖
pthread_rwlock_t rwlock=PTHREAD_RWLOCK_INITIALIZER;

int pthread_rwlock_rdlock(pthread_rwlock_t *rwlock)? // 加讀鎖,阻塞
int pthread_rwlock_wrlock(pthread_rwlock_t *rwlock)? // 加寫鎖,阻塞
int pthread_rwlock_unlock(pthread_rwlock_t *rwlock)? // 釋放讀鎖或者寫鎖

int pthread_rwlock_tryrdlock(pthread_rwlock_t *rwlock)? // 嘗試加讀鎖,非阻塞
int pthread_rwlock_trywrlock(pthread_rwlock_t *rwlock)? // 嘗試加寫鎖,非阻塞

例子:

#include <stdio.h>
#include <pthread.h>

pthread_rwlock_t rwlock=PTHREAD_RWLOCK_INITIALIZER;

void *read(void *arg) {
    while(1) {
        pthread_rwlock_rdlock(&rwlock);
        rintf("read message.\n");
        sleep(1);
        pthread_rwlock_unlock(&rwlock);
        sleep(1);
    }
}
void *write(void *arg) {
    while(1) {
        pthread_rwlock_wrlock(&rwlock);
        printf("write message.\n");
        sleep(1);
        pthread_rwlock_unlock(&rwlock);
        sleep(1);
    }
}

int main(int argc,char *argv[]) {
    pthread_t t1,t2,t3;
    pthread_create(&t1, NULL, &read, NULL);
    pthread_create(&t2, NULL, &read, NULL);

    pthread_create(&t3, NULL, &write, NULL);

    pthread_join(t1, NULL);
    return 0;
}

屏障

屏障(barrier)是用戶協(xié)調(diào)多個(gè)線程并行工作的同步機(jī)制。屏障允許每個(gè)線程等待,直到所有的合作線程都到達(dá)某一點(diǎn),然后所有線程都從該點(diǎn)繼續(xù)執(zhí)行。pthread_join函數(shù)就是一種屏障,允許一個(gè)線程等待,直到另一個(gè)線程退出。但屏障對(duì)象的概念更廣,允許任意數(shù)量的線程等待,直到所有的線程完成處理工作,而線程不需要退出,當(dāng)所有的線程達(dá)到屏障后可以接著工作。

相關(guān)方法:

// 創(chuàng)建屏障
int pthread_barrier_init(pthread_barrier_t *barrier,const pthread_barrrierattr_t *attr,unsigned int count)

// 阻塞等待,直到所有線程都到達(dá)
int pthread_barrier_wait(pthread_barrier_t *barrier)

例子:

#include <stdio.h>
#include <pthread.h>

pthread_barrier_t barrier;

void *go(void *arg){
    sleep (rand () % 10);
    printf("%lu is arrived.\n", pthread_self());
    pthread_barrier_wait(&barrier);
    printf("%lu go shopping...\n", pthread_self());
}

int main() {
    pthread_barrier_init(&barrier, NULL, 3);

    pthread_t t1,t2,t3;
    pthread_create(&t1, NULL, &go, NULL);
    pthread_create(&t2, NULL, &go, NULL);
    pthread_create(&t3, NULL, &go, NULL);

    pthread_join(t1, NULL);
    return 0;
}

以上就是Linux中實(shí)現(xiàn)線程同步的6種方法的詳細(xì)內(nèi)容,更多關(guān)于Linux線程同步的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

  • Vim 強(qiáng)制保存只讀類型文件的方法

    Vim 強(qiáng)制保存只讀類型文件的方法

    你是否會(huì)和我一樣經(jīng)常碰到這樣的情景:在VIM中編輯了一個(gè)系統(tǒng)配置文件,當(dāng)需要保存時(shí)才發(fā)現(xiàn)當(dāng)前的用戶對(duì)該文件沒(méi)有寫入的權(quán)限。這個(gè)時(shí)候就需要強(qiáng)制保存只讀類型文件的方法了,這篇文章就介紹了Vim強(qiáng)制保存只讀類型文件的方法,需要的朋友可以參考借鑒,下面來(lái)一起看看吧。
    2017-01-01
  • linux安裝jdk,tomcat 配置vsftp遠(yuǎn)程連接的步驟

    linux安裝jdk,tomcat 配置vsftp遠(yuǎn)程連接的步驟

    這篇文章主要介紹了linux安裝jdk,tomcat 配置vsftp遠(yuǎn)程連接,需要的朋友可以參考下
    2015-04-04
  • ssh遠(yuǎn)程登陸沒(méi)有用戶名和主機(jī)名的解決方法

    ssh遠(yuǎn)程登陸沒(méi)有用戶名和主機(jī)名的解決方法

    這篇文章主要給大家分享了ssh遠(yuǎn)程登陸沒(méi)有用戶名和主機(jī)名的解決方法,文中介紹的非常詳細(xì),相信對(duì)大家具有一定的參考價(jià)值,需要的朋友們下面來(lái)一起看看吧。
    2017-03-03
  • Apache 獲取真實(shí)ip的配置的實(shí)現(xiàn)方法

    Apache 獲取真實(shí)ip的配置的實(shí)現(xiàn)方法

    這篇文章主要介紹了Apache 獲取真實(shí)ip的配置的實(shí)現(xiàn)方法的相關(guān)資料,希望通過(guò)本文能幫助到大家,讓大家實(shí)現(xiàn)這樣的功能,需要的朋友可以參考下
    2017-10-10
  • 在Ubuntu上打不開GitHub的完整解決方法

    在Ubuntu上打不開GitHub的完整解決方法

    當(dāng)你滿心歡喜打開Ubuntu準(zhǔn)備推送代碼時(shí),突然發(fā)現(xiàn)終端里的git?push卡成狗,瀏覽器里的GitHub頁(yè)面直接變成Whoa?there!警告頁(yè)面,本文就這個(gè)問(wèn)題小編給大家介紹了當(dāng)你在Ubuntu上打不開GitHub時(shí)的終極自救指南,需要的朋友可以參考下
    2025-09-09
  • Apache中配置支持CORS(跨域資源共享)實(shí)例

    Apache中配置支持CORS(跨域資源共享)實(shí)例

    這篇文章主要介紹了Apache中配置支持CORS(跨域資源共享)實(shí)例,本文給出了一個(gè)完整的apache、PHP、JavaScript結(jié)合實(shí)現(xiàn)的跨域資源共享實(shí)例,需要的朋友可以參考下
    2015-01-01
  • Linux netfilter/iptables知識(shí)點(diǎn)詳解

    Linux netfilter/iptables知識(shí)點(diǎn)詳解

    在本篇文章里小編給大家整理的是關(guān)于Linux netfilter/iptables知識(shí)點(diǎn)詳解,有興趣的朋友們可以參考下。
    2020-03-03
  • 如何通過(guò)其他主機(jī)查看Apahce服務(wù)器的運(yùn)行狀態(tài)

    如何通過(guò)其他主機(jī)查看Apahce服務(wù)器的運(yùn)行狀態(tài)

    這篇文章主要介紹了如何通過(guò)其他主機(jī)查看Apahce服務(wù)器的運(yùn)行狀態(tài),需要的朋友可以參考下
    2016-04-04
  • CentOs 7.*中配置安裝phpMyAdmin的完整步驟記錄

    CentOs 7.*中配置安裝phpMyAdmin的完整步驟記錄

    phpMyAdmin是一個(gè)以PHP為基礎(chǔ),以Web-Base方式架構(gòu)在網(wǎng)站主機(jī)上的MySQL的資料庫(kù)管理工具。下面這篇文章主要給大家介紹了關(guān)于CentOs 7.*中配置安裝phpMyAdmin的相關(guān)資料,需要的朋友可以參考借鑒,下面來(lái)一起看看吧
    2018-07-07
  • Linux 環(huán)境變量詳解及實(shí)例

    Linux 環(huán)境變量詳解及實(shí)例

    這篇文章主要介紹了Linux 環(huán)境變量詳解及實(shí)例的相關(guān)資料,需要的朋友可以參考下
    2017-02-02

最新評(píng)論

东丰县| 稷山县| 广安市| 五华县| 乌兰察布市| 阿合奇县| 兴海县| 溆浦县| 贡嘎县| 溆浦县| 忻州市| 蓝山县| 江安县| 陆河县| 诸城市| 读书| 黑河市| 永胜县| 谷城县| 凉城县| 平定县| 县级市| 鄱阳县| 阳新县| 商南县| 镇江市| 开远市| 磴口县| 临高县| 浦北县| 百色市| 陆丰市| 永嘉县| 宝山区| 昌吉市| 武义县| 珲春市| 郁南县| 牡丹江市| 延津县| 克拉玛依市|