1. 程式人生 > >C++互斥鎖

C++互斥鎖

#include<pthread.h>

pthread_mutex_t abc;               //建立一個名為abc的semaphore變數;

pthread_mutex_init(&abc,NULL) ;   //初始化     (第一個為互斥變數地址,第二個為互斥變數屬性,NULL即為預設快速互斥鎖,即abc=1)

int pthread_mutex_lock(&abc)  ;   // P一下abc              成功返回0

int pthread_mutex_unlock(&abc)  ;   // V一下abc        成功返回0

注意建立執行緒的那一瞬間繼承前面的所有資料,之後執行緒與其他執行緒之間的資料就分開了

未加鎖版:

#include<stdio.h>
#include<pthread.h>
using namespace std;

 int num=100;
 void* tprocess1(void* args)
 {
 	while(num>0){
	 
 	int i=num;
 	printf("tprocess1--%d\n",i);
 	i--;
 	num=i;
 	    }
 	return NULL;    
 }

 void* tprocess2(void* args)
 {
 	while(num>0){
	 
 	int i=num;
 	printf("tprocess2--%d\n",i);
 	i--;
 	num=i;
 	    }
 	return NULL;    
 }


   int main()
    {
    	pthread_t t1;
    	pthread_t t2;
    	pthread_create(&t1,NULL,tprocess1,NULL);  
    	pthread_create(&t2,NULL,tprocess2,NULL);   //注意這句開始的時候num可能已經不是為100了,假設為97,則tprocess2繼承97往下輸出
    	pthread_join(t1,NULL);
    	pthread_join(t2,NULL);                  
    	return 0;
	}

加鎖版:(規規矩矩的從100輸出到0)
#include<stdio.h>
#include<pthread.h>
using namespace std;

 pthread_mutex_t abc;
 int num=100;
 void* tprocess1(void* args)
 {
 	while(num>0){
	 pthread_mutex_lock(&abc);
 	int i=num;
 	printf("tprocess1--%d\n",i);
 	i--;
 	num=i;
 	pthread_mutex_unlock(&abc);
 	    }
 	return NULL;    
 }

 void* tprocess2(void* args)
 {
 	while(num>0){
	 pthread_mutex_lock(&abc);
 	int i=num;
 	printf("tprocess2--%d\n",i);
 	i--;
 	num=i;
 	pthread_mutex_unlock(&abc);
 	    }
 	return NULL;    
 }


   int main()
    {
    	pthread_t t1;
    	pthread_t t2;
    	
    	pthread_mutex_init(&abc,NULL); 
    	
    	pthread_create(&t1,NULL,tprocess1,NULL);
    	pthread_create(&t2,NULL,tprocess2,NULL);
    	pthread_join(t1,NULL);
    	pthread_join(t2,NULL);
    	return 0;
	}