linux實現線程同步有幾種方式

6種方式:1、互斥鎖,本質就是一個特殊的全局變量,擁有lock和unlock兩種狀態;2、自旋鎖,是一個死循環,不停的輪詢;3、信號量,用于控制訪問有限共享資源的線程數;4、條件變量,可以讓調用線程在滿足特定條件的情況下運行,不滿足條件時阻塞等待被喚醒;5、讀寫鎖,一次只能有一個線程可以占有寫模式的讀寫鎖;6、屏障,是用戶協調多個線程并行工作的同步機制。

linux實現線程同步有幾種方式

本教程操作環境:linux7.3系統、Dell G3電腦。

linux中實現線程同步的6種方法

下面是一個線程不安全的例子:

#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=%dn", ticket_num);     return 0; }

運行結果如下:

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

最后運行的結果不是固定的,有可能是0、-1,如果有這個ticket_num變量代表是庫存的話,那么就會出現庫存為負數的情況,所以需要引入線程同步來保證線程安全。

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

互斥鎖

互斥鎖本質就是一個特殊的全局變量,擁有lock和unlock兩種狀態,unlock的互斥鎖可以由某個線程獲得,當互斥鎖由某個線程持有后,這個互斥鎖會鎖上變成lock狀態,此后只有該線程有權力打開該鎖,其他想要獲得該互斥鎖的線程都會阻塞,直到互斥鎖被解鎖。

互斥鎖的類型:

  • 普通鎖(PTHREAD_MUTEX_NORMAL):互斥鎖默認類型。當一個線程對一個普通鎖加鎖以后,其余請求該鎖的線程將形成一個 等待隊列,并在該鎖解鎖后按照優先級獲得它,這種鎖類型保證了資源分配的公平性。一個 線程如果對一個已經加鎖的普通鎖再次加鎖,將引發死鎖;對一個已經被其他線程加鎖的普 通鎖解鎖,或者對一個已經解鎖的普通鎖再次解鎖,將導致不可預期的后果。

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

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

  • 默認鎖(PTHREAD_MUTEX_ default):一個線程如果對一個已經加鎖的默認鎖再次加鎖,或者雖一個已經被其他線程加鎖的默 認鎖解鎖,或者對一個解鎖的默認鎖解鎖,將導致不可預期的后果;這種鎖實現的時候可能 被映射成上述三種鎖之一。

相關方法:

// 靜態方式創建互斥鎖 pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER?   // 動態方式創建互斥鎖,其中參數mutexattr用于指定互斥鎖的類型,具體類型見上面四種,如果為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=%dn", ticket_num);     return 0; }

自旋鎖

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

相關方法:

int pthread_spin_init(pthread_spinlock_t *lock, int pshared)? // 創建自旋鎖  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=%dn", ticket_num);     return 0; }

信號量

信號量是一個計數器,用于控制訪問有限共享資源的線程數。

相關方法:

// 創建信號量 // pshared:一般取0,表示調用進程的信號量。非0表示該信號量可以共享內存的方式,為多個進程所共享(Linux暫不支持)。 // value:信號量的初始值,可以并發訪問的線程數。 int sem_init (sem_t* sem, int pshared, unsigned int value);  int sem_wait (sem_t* sem); // 信號量減1,信號量為0時就會阻塞  int sem_trywait (sem_t* sem); // 信號量減1,信號量為0時返回-1,不阻塞  int sem_timedwait (sem_t* sem, const struct timespec* abs_timeout); // 信號量減1,信號量為0時阻塞,直到abs_timeout超時返回-1  int sem_post (sem_t* sem); // 信號量加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個線程同時訪問共享資源,與互斥量等價     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=%dn", ticket_num);     return 0; }

條件變量

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

條件變量常用于生產者與消費者模型。

相關方法:

pthread_cond_t cond=PTHREAD_COND_INITIALIZER; // 創建條件變量,一個互斥鎖可以對應多個條件變量  int pthread_cond_wait (pthread_cond_t* cond,pthread_mutex_t* mutex); // 阻塞等待條件滿足,同時釋放互斥鎖mutex  int pthread_cond_timedwait (pthread_cond_t* cond,     pthread_mutex_t* mutex,     const struct timespec* abstime); // 帶超時的阻塞等待條件滿足,同時釋放互斥鎖mutex  // 從條件變量cond中喚出一個線程,令其重新獲得原先的互斥鎖 // 被喚出的線程此刻將從pthread_cond_wait函數中返回,但如果該線程無法獲得原先的鎖,則會繼續阻塞在加鎖上。 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; }

讀寫鎖

讀寫鎖可以有三種狀態:讀模式下加鎖狀態,寫模式下加鎖狀態,不加鎖狀態。一次只有一個線程可以占有寫模式的讀寫鎖,但是多個線程可以同時占有讀模式的讀寫鎖。讀寫鎖也叫做共享-獨占鎖,當讀寫鎖以讀模式鎖住時,它是以共享模式鎖住的,當它以寫模式鎖住時,它是以獨占模式鎖住的,讀讀共享,讀寫互斥。

一次只能有一個線程可以占有寫模式的讀寫鎖,但是多個線程可以同時戰友讀模式的讀寫鎖。因此與互斥量相比,讀寫鎖允許更高的并行性。讀寫鎖非常適合對數據結構讀的次數遠大于寫的情況。

相關方法:

// 創建讀寫鎖 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)是用戶協調多個線程并行工作的同步機制。屏障允許每個線程等待,直到所有的合作線程都到達某一點,然后所有線程都從該點繼續執行。pthread_join函數就是一種屏障,允許一個線程等待,直到另一個線程退出。但屏障對象的概念更廣,允許任意數量的線程等待,直到所有的線程完成處理工作,而線程不需要退出,當所有的線程達到屏障后可以接著工作。

相關方法:

// 創建屏障 int pthread_barrier_init(pthread_barrier_t *barrier,const pthread_barrrierattr_t *attr,unsigned int count)  // 阻塞等待,直到所有線程都到達 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視頻教程

? 版權聲明
THE END
喜歡就支持一下吧
點贊15 分享