線程中互斥鎖使用的步驟與信號量相似!
1、首先定義互斥鎖變量,並初始化
pthread_mutex_t mutex_lock;
pthread_mutex_init(&mutex_lock,NULL);
2、在操作前對互斥量進行加鎖操作
pthread_mutex_lock(&mutex_lock);
3、操作完畢后進行解鎖操作
pthread_mutex_unlock(&mutex_lock);
所有操作均在加鎖和解鎖操作之間進行,保證同時僅僅對有一個操作對關鍵變量或是區域進行操作。
下面是自己寫的一個小程序,對主函數對變量自加操作,而線程函數進行自減操作。
(該程序有個小bug,看官可執行運行一下,就知道結果了,高手一看就知道問題在哪里,哈哈!賣個關子!)
pthread_mutex_lock(&mutex_lock);對某個互斥鎖變量進行加鎖操作時,當該變量已經被另外一個線程鎖住時,該線程會被阻塞(英文原文為block),可以理解為休眠。
由操作系統基本原理可知,當進程處於就緒狀態時,才會獲得處理機的時間片,換句話說就是能能被調度到處理機上執行,而阻塞狀態則不能。
因此一個線程被阻塞后,將不會執行,處於等待狀態,通常是等待某個事件發生或到來。因此,一個對已經加鎖的變量進行加鎖的線程將被阻塞,其只能等待另外一個線程解鎖,才能繼續執行。
1 #include<stdio.h> 2 #include<unistd.h> 3 #include<stdlib.h> 4 #include<pthread.h> 5 #include<string.h> 6 #include<errno.h> 7 8 void *thread_function(void *arg); 9 pthread_mutex_t mutex_lock; 10 int globaltmp=0; 11 int main(){ 12 int res; 13 pthread_t pthread_tmp; 14 pthread_mutex_init(&mutex_lock,NULL); 15 pthread_mutex_lock(&mutex_lock); 16 res = pthread_create(&pthread_tmp,NULL,thread_function,NULL); 17 if(res != 0){ 18 perror("thread creation failed!"); 19 exit(EXIT_FAILURE); 20 } 21 while(1){ 22 pthread_mutex_unlock(&mutex_lock); 23 sleep(2); 24 globaltmp++; 25 printf("in the main func,globaltmp=%d\n",globaltmp); 26 res = pthread_mutex_lock(&mutex_lock); 27 // if(res == EDEADLK) 28 { 29 // printf("it has been locked in the thread!\n"); 30 } 31 // printf(" main func res =%d\n",res); 32 sleep(2); 33 } 34 res = pthread_join(pthread_tmp,NULL); 35 if(res != 0 ){ 36 perror("thread join is failure"); 37 exit(EXIT_FAILURE); 38 } 39 printf("thread joined!\n"); 40 pthread_mutex_destroy(&mutex_lock); 41 return 0; 42 } 43 void *thread_function(void *arg){ 44 int res ; 45 res = pthread_mutex_lock(&mutex_lock); 46 if(res == EDEADLK) 47 printf("it has been locked in the main!\n"); 48 while(1) 49 { 50 pthread_mutex_unlock(&mutex_lock); 51 sleep(1); 52 globaltmp--; 53 printf("in the pthread func,globaltmp=%d\n",globaltmp); 54 // printf("I am in the pthread func\n"); 55 res = pthread_mutex_lock(&mutex_lock); 56 // printf("thread func res=%d\n",res); 57 // if(res == EDEADLK) 58 // printf("it has been locked in the main!\n"); 59 sleep(1); 60 } 61 pthread_exit(NULL); 62 }