C++互斥锁

#include<pthread.h>

pthread_mutex_t abc;               //创建一个名为abc的semaphore变量;

pthread_mutex_init(&abc,NULL) ;   //初始化     (第一个为互斥变量地址,第二个为互斥变量属性,NULL即为默认快速互斥锁,即abc=1)

pthread_mutex_destroy(&abc)        //销毁锁

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);

        pthread_mutex_destroy(&abc) 

    	return 0;
	}

 

 

 

 

 

 
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值