1.多線程并發?
1).多線程并發引例
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <assert.h>
#include <pthread.h>int wg=0;
void *fun(void *arg)
{for(int i=0;i<1000;i++){wg++;printf("wg=%d\n",wg);}
}
int main()
{pthread_t id[5];for(int i=0;i<5;i++){pthread_create(&id[i],NULL,fun,NULL);}for(int i=0;i<5;i++){pthread_join(id[i],NULL);}exit(0);
}
?
運行結果出錯!!!
原子操作的概念:一個或多個指令的序列,對外是不可分的;即沒有其他進程可以看到其中間狀態或者中斷此操作;
而wg++不是一個原子操作;
這種情況也不是每一次都發生,也不是一定發生了多少次.這種情況就是最可怕的,給人的感覺是時對時錯;
注意,只有一個處理器的時候這種情況出現的概率是非常小的,同一時刻只有一個線程在運行,不容易出現兩個線程同時去獲取i的值的情況,但是也會發生;?
2).解決多線程并發---線程同步
多線程并發就有可能出現問題的,比如兩個線程都去在鏈表中插入,比如都在做尾插,都在找尾巴,那么多線程就會出問題;
怎么解決這個問題呢?就是線程同步;
在一個多線程程序里,默認情況下,只有一個errno變量供所有的線程共享.在一個線程準備獲取剛才的錯誤代碼時,該變量很容易被另一個線程中的函數調用所改變.
2.線程同步的概念:
一個進程中的所有線程共享同一個地址空間和諸如打開的文件之類的其他資源.一個線程對資源的任何修改都會影響同一個進程中其他線程的環境.因此,需要同步各種線程的活動,以便它們互不干涉且不破壞數據結構.例如,如果兩個線程都試圖同時往一個雙向鏈表中增加一個元素,則可能會丟失一個元素或者破壞鏈表結構.
同步就是讓所有線程按照一定的規則執行,使得其正確性和效率都有跡可循.線程同步的手段就是對線程之間的穿插進行控制.
線程同步指的是當一個線程在對某個臨界資源進行操作時,其他線程都不可以對這個資源進行操作,直到該線程完成操作, 其他線程才能操作,也就是協同步調,讓線程按預定的先后次序進行運行。
臨界資源:同一時刻,只允許被一個進程或者線程訪問的資源;(比如打印機)
臨界區:訪問臨界資源的代碼段;
線程同步的方法有四種:互斥鎖、信號量、條件變量、讀寫鎖.
3.互斥鎖:線程同步方法一
(1)互斥鎖接口
int pthread_mutex_init(pthread_mutex_t *mutex, pthread_mutexattr_t *attr);
attr:鎖的屬性,不需要傳空即可int pthread_mutex_lock(pthread_mutex_t *mutex); int pthread_mutex_unlock(pthread_mutex_t *mutex);int pthread_mutex_destroy(pthread_mutex_t *mutex);
//注意,互斥鎖mutex都需要傳地址,因為要改變它;
(2)互斥鎖例1(解決多線程并發問題)
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <assert.h>
#include <pthread.h>pthread_mutex_t mutex;
int wg=0;
void *fun(void *arg)
{for(int i=0;i<1000;i++){pthread_mutex_lock(&mutex);wg++;pthread_mutex_unlock(&mutex);printf("wg=%d\n",wg);}
}
int main()
{pthread_t id[5];pthread_mutex_init(&mutex,NULL);for(int i=0;i<5;i++){pthread_create(&id[i],NULL,fun,NULL);}for(int i=0;i<5;i++){pthread_join(id[i],NULL);}pthread_mutex_destroy(&mutex);exit(0);
}
?
(3)互斥鎖例2(共享資源(打印機)使用問題)
主線程和函數線程模擬訪問打印機,主線程輸出第一個字符‘ A’表示開始使用打印機,輸出第二個字符‘ A’表示結束使用,函數線程操作與主線程相同。
(由于打印機同一時刻只能被一個線程使用,所以輸出結果不應該出現ABAB交替出現) :
原來是用信號量進行控制的,我們這里也可以用互斥鎖進行同步;
示例代碼:
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <unistd.h>
#include <string.h>
#include <pthread.h>pthread_mutex_t mutex;void *thread_fun(void *arg)
{int i=0;for(;i<5;i++){pthread_mutex_lock(&mutex);write(1,"B",1);int n=rand()%3;sleep(n);write(1,"B",1);pthread_mutex_unlock(&mutex);n=rand()%3;sleep(n);}pthread_exit(NULL);
}int main()
{pthread_t id;pthread_mutex_init(&mutex,NULL);pthread_create(&id,NULL,thread_fun,NULL);int i=0;for(;i<5;i++){pthread_mutex_lock(&mutex);write(1,"A",1);int n=rand()%3;sleep(n);write(1,"A",1);pthread_mutex_unlock(&mutex);n=rand()%3;sleep(n);}pthread_join(id,NULL);pthread_mutex_destroy(&mutex);exit(0);
}
4.信號量(線程)線程同步方法二
(1)信號量接口
信號量的類型:
sem_t 全局定義一個sem_t類型的信號量
注意,必須要加頭文件:#include <semaphore.h>int sem_init(sem_t *sem, int pshared, unsigned int value);
//信號量的初始化
//sem_init()在sem指向的地址初始化未命名的信號量。這個value參數指定信號量的初始值(第三個參數)。
//pshared:設置信號量是否在進程間共享,Linux不支持,一般給0; (非0為共享)int sem_wait(sem_t *sem);
//P操作,wait表示等待,相當于是等待獲取資源,那么就是P操作int sem_post(sem_t *sem);
//V操作int sem_destroy(sem_t *sem);
//銷毀信號量
(2)信號量例1(全局變量++正確性問題)
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <unistd.h>
#include <string.h>
#include <semaphore.h>
#include <pthread.h>sem_t sem;
int wg=0;
void *fun(void *arg)
{for(int i=0;i<1000;i++){sem_wait(&sem);wg++;sem_post(&sem);printf("wg=%d\n",wg);}
}
int main()
{pthread_t id[5];sem_init(&sem,0,1);for(int i=0;i<5;i++){pthread_create(&id[i],NULL,fun,NULL);}for(int i=0;i<5;i++){pthread_join(id[i],NULL);}sem_destroy(&sem);exit(0);
}
(3)信號量例2
主線程獲取用戶輸入,函數線程將用戶輸入的數據存儲到文件中;
//semtest.c
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <string.h>
#include <unistd.h>
#include <pthread.h>
#include <semaphore.h>
#include <fcntl.h>char buff[128]={0};
//主線程完成獲取用戶數據的數據,并存儲在全局數組buff中;sem_t sem1;
sem_t sem2;void *PthreadFun(void *arg)
{int fd=open("a.txt",O_RDWR|O_CREAT,0664);//O_RDWR:讀寫方式打開assert(fd!=-1);//函數線程完成將用戶輸入的數據存儲到文件中while(1){sem_wait(&sem2);if(strncmp(buff,"end",3)==0){break;}write(fd,buff,strlen(buff));memset(buff,0,128);sem_post(&sem1);}sem_destroy(&sem1);sem_destroy(&sem2);
}int main()
{sem_init(&sem1,0,1);sem_init(&sem2,0,0);pthread_t id;int res=pthread_create(&id,NULL,PthreadFun,NULL);assert(res==0);//主線程完成獲取用戶數據的數據,并存儲在全局數組buff中;while(1){sem_wait(&sem1);printf("please input data:");fflush(stdout);fgets(buff,128,stdin);buff[strlen(buff)-1]=0;sem_post(&sem2);if(strncmp(buff,"end",3)==0){break;}}pthread_exit(NULL);
}
(3)信號量例3
(以前是用多進程做的,封裝比較麻煩.那如果用多線程的信號量做,如何做呢)
剛開始先打印A,所以信號量為1,后面的B和C不能打印,所以后面兩個信號量的初始值都為0;
?上面是多進程的思路圖,多線程的思路和多進程是一樣的.
不使用信號量,代碼如下:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include <semaphore.h>void * funa(void *arg)
{for(int i=0;i<5;i++){printf("A");fflush(stdout);sleep(1);//這個其實不需要的,只是為了便于觀察程序的執行;}
}void * funb(void *arg)
{for(int i=0;i<5;i++){printf("B");fflush(stdout);sleep(1);//這個其實不需要的,只是為了便于觀察程序的執行;}
}void * func(void *arg)
{for(int i=0;i<5;i++){printf("C");fflush(stdout);sleep(1);//這個其實不需要的,只是為了便于觀察程序的執行;}
}int main()
{pthread_t id[3];pthread_create(&id[0],NULL,funa,NULL);pthread_create(&id[1],NULL,funb,NULL);pthread_create(&id[2],NULL,func,NULL);for(int i=0;i<3;i++){pthread_join(id[i],NULL);}exit(0);}
?執行三次,三次不一樣的結果
?如何使用信號量呢?
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include <semaphore.h>//加入1-15 代碼
sem_t sema;//1
sem_t semb;//2
sem_t semc;//3void * funa(void *arg)
{for(int i=0;i<5;i++){sem_wait(&sema);//4相當于圖上的ps1;printf("A");fflush(stdout);sem_post(&semb);//5相當于圖上的vs2;sleep(1);//這個其實不需要的,只是為了便于觀察程序的執行;}
}void * funb(void *arg)
{for(int i=0;i<5;i++){sem_wait(&semb);//6相當于圖上的ps2;printf("B");fflush(stdout);sem_post(&semc);//7相當于圖上的vs3;sleep(1);//這個其實不需要的,只是為了便于觀察程序的執行;}
}void * func(void *arg)
{for(int i=0;i<5;i++){sem_wait(&semc);//8相當于圖上的ps3;printf("C");fflush(stdout);sem_post(&sema);//9相當于圖上的vs1;sleep(1);//這個其實不需要的,只是為了便于觀察程序的執行;}
}int main()
{sem_init(&sema,0,1);//10也可以這么理解,第二個參數一直為0,因為不能在進程間共享;sem_init(&semb,0,0);//11sem_init(&semc,0,0);//12pthread_t id[3];pthread_create(&id[0],NULL,funa,NULL);pthread_create(&id[1],NULL,funb,NULL);pthread_create(&id[2],NULL,func,NULL);for(int i=0;i<3;i++){pthread_join(id[i],NULL);}sem_destroy(&sema);//13sem_destroy(&semb);//14sem_destroy(&semc);//15exit(0);}
?
5.條件變量(線程同步方法三)
1)條件變量的接口:
#include <pthread.h>int pthread_cond_init(pthread_cond_t *cond, pthread_condattr_t *attr);int pthread_cond_wait(pthread_cond_t *cond, pthread_mutex_t *mutex);
//將條件變量添加到等待隊列中,阻塞,等待被喚醒;第一個參數是條件變量的地址,第二個參數是互斥鎖;也就是說條件變量往往伴隨著互斥鎖的使用;int pthread_cond_signal(pthread_cond_t *cond); //喚醒單個線程int pthread_cond_broadcast(pthread_cond_t *cond); //喚醒所有等待的線程int pthread_cond_destroy(pthread_cond_t *cond);//銷毀條件變量
?例題:主函數輸入數據到全局變量buf中.
主線程負責從鍵盤獲取數據,獲取到數據之后把數據寫入到buff中,我們就認為條件滿足了,我們就去喚醒等待著的兩個線程,讓其中的某一個線程將buff中的數據打印出去;
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <pthread.h>pthread_cond_t cond;
pthread_mutex_t mutex;//條件變量一般伴隨著互斥鎖的使用;char buff[128]={0};void *work_thread(void *arg)
{char *thread_name=(char *)arg;while(1){pthread_mutex_lock(&mutex);pthread_cond_wait(&cond,&mutex);pthread_mutex_unlock(&mutex);if(strncmp(buff,"end",3)==0){break;//1}printf("%s %s",thread_name,buff);//2}
}int main()
{pthread_cond_init(&cond,NULL);pthread_mutex_init(&mutex,NULL);pthread_t id1,id2;pthread_create(&id1,NULL,work_thread,"thread:1");pthread_create(&id2,NULL,work_thread,"thread:2");while(1){fgets(buff,128,stdin);if(strncmp(buff,"end",3)==0){pthread_cond_broadcast(&cond);break;}else{pthread_cond_signal(&cond);}}pthread_join(id1,NULL);pthread_join(id2,NULL);pthread_mutex_destroy(&mutex);pthread_cond_destroy(&cond);printf("main over\n");exit(0);
}
?
pthread_cond_broadcast函數以廣播的方式喚醒所有等待目標條件變量的線程; pthread_cond_signal函數用于喚醒一個等待目標條件變量的線程.至于哪個線程將被喚醒,則取決于線程的優先級和調度策略.有時候我們可能想喚醒一個指定的線程,但是pthread沒有對該需求提供解決方法.
pthread_cond_wait函數用于等待目標條件變量.mutex參數是用于保護條件變量的互斥鎖,以確保pthread_conde_wait操作的原子性.在調用pthread_cond_wait前,必須確保互斥鎖mutex已經加鎖,否則將導致不可預期的結果.pthread_cond_wait函數執行時,首先把調用線程放入條件變量的等待隊列中,然后將互斥鎖mutex解鎖.可見,從pthread_cond_wait開始執行到其調用線程被放入條件變量的等待隊列之間的這段時間內,pthread_cond_signal和pthread_cond_broadcast等函數不會修改條件變量.換言之,pthread_cond_wait函數不會錯過目標條件變量的任何變化.當pthread_cond_wait函數成功返回時,互斥鎖mutex將再次被鎖上.
6.讀寫鎖(線程同步方法四)
讀寫鎖保證了更高的并發性;
讀寫鎖適用讀的場景比較多的場景;
#include <pthread.h>
int pthread_rwlock_init(pthread_rwlock_t *rwlock, pthread_rwlockattr_t *attr);//第一個參數是鎖的地址,第二個參數是鎖的屬性
int pthread_rwlock_rdlock(pthread_rwlock_t *rwlock);//加讀鎖
int pthread_rwlock_wrlock(pthread_rwlock_t *rwlock);//加寫鎖
int pthread_rwlock_unlock(pthread_rwlock_t *rwlock);//解鎖,不管加的讀鎖還是寫鎖,都是通過unlock解鎖;
int pthread_rwlock_destroy(pthread_rwlock_t *rwlock);//銷毀 //讀模式下的加鎖狀態,寫模式下的加鎖狀態,不加鎖的狀態
///模擬 //我們可以創建3個線程,兩個線程進行讀操作,一個線程進行寫操作; //我們模擬一下這個,可以讓兩個讀操作同時操作;但是讀和寫是不能同時操作的;
我們首先來看沒有控制的代碼:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include <semaphore.h>pthread_rwlock_t rwlock;
void * fun_read(void * arg)
{char *s=(char *)arg;for(int i=0;i<5;i++){printf("%s: start\n",s);int n=rand()%3;sleep(n);printf("%s: end\n",s);n=rand()%3;sleep(n);}
}void * fun_write(void * arg)
{char *s=(char *)arg;for(int i=0;i<5;i++){printf("%s: start\n",s);int n=rand()%3;sleep(n);printf("%s: end\n",s);n=rand()%3;sleep(n);}
}int main()
{pthread_rwlock_init(&rwlock,NULL);pthread_t id1,id2,id3;pthread_create(&id1,NULL,fun_read,"第一個讀線程:");pthread_create(&id2,NULL,fun_read,"第二個讀線程:");pthread_create(&id3,NULL,fun_write,"第一個寫線程:");pthread_join(id1,NULL);pthread_join(id2,NULL);pthread_join(id3,NULL);pthread_rwlock_destroy(&rwlock);exit(0);}
?
如何運用讀寫鎖呢?代碼如下:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include <semaphore.h>pthread_rwlock_t rwlock;
void * fun_read(void * arg)
{char *s=(char *)arg;for(int i=0;i<5;i++){pthread_rwlock_rdlock(&rwlock);//1pthread_rwlock_rdlock命名含有:線程的_讀寫鎖_讀鎖;printf("%s: start\n",s);int n=rand()%3;sleep(n);printf("%s: end\n",s);pthread_rwlock_unlock(&rwlock);//2pthread_rwlock_unlock命名含有:線程的_讀寫鎖_解鎖;n=rand()%3;sleep(n);}
}void * fun_write(void * arg)
{char *s=(char *)arg;for(int i=0;i<5;i++){pthread_rwlock_wrlock(&rwlock);//3pthread_rwlock_rwlock命名含有:線程的_讀寫鎖_寫鎖;printf("%s: start\n",s);int n=rand()%3;sleep(n);printf("%s: end\n",s);pthread_rwlock_unlock(&rwlock);//4pthread_rwlock_unlock命名含有:線程的_讀寫鎖_解鎖;n=rand()%3;sleep(n);}
}int main()
{pthread_rwlock_init(&rwlock,NULL);pthread_t id1,id2,id3;pthread_create(&id1,NULL,fun_read,"r1");pthread_create(&id2,NULL,fun_read,"r2");pthread_create(&id3,NULL,fun_write,"w1");pthread_join(id1,NULL);pthread_join(id2,NULL);pthread_join(id3,NULL);pthread_rwlock_destroy(&rwlock);exit(0);}
?
?我們要保證寫的start和end中間是不能出現讀的,而且讀兩個可以,讀的中間不能有寫;