pthread_mutex_lock互斥锁的使用

5 篇文章 0 订阅
4 篇文章 0 订阅

直接上个例子几简单哦!
现在我姑且认为互斥锁就是为了保护共享变量(现在看到的这个共享变量就是全局变量)而设置的,因为还没学那么多。
//互斥锁的使用

#include<errno.h>
#include< cstring>
#include< iostream>
#include< cstdlib>
#include<sys/socket.h>
#include<sys/types.h>
#include<netinet/in.h>
#include<unistd.h>
#include< ctime>
#include<arpa/inet.h>
using namespace std;
const int NLOOP=10;
int counter,n;  //在这里counter就是那个我想保护的共享变量罗
void std_err(string s)
{
 cout<<s<<"failed"<<endl;
 exit(0);
}
pthread_mutex_t counter_mutex=PTHREAD_MUTEX_INITIALIZER;  //互斥锁变量设置为静态分配的
void* doit(void* vptr)
{     
 int i,val;
 for(i=0;i<NLOOP;i++)
 {  
  sleep(1);
  n=pthread_mutex_lock(&counter_mutex);  //为互斥锁counter_mutex上锁,在操作全局变量conuter之前必须上锁
  if(n!=0)
  std_err("pthread_mutex_lock");
  val=counter;
  cout<<pthread_self()<<":"<<val+1<<endl;
  n=pthread_mutex_unlock(&counter_mutex);   //为互斥变量counter_mutex解锁
   if(n!=0)
  std_err("pthread_mutex_unlock");
 }
 return NULL;
}
int main()
{
 pthread_t tidA,tidB;
 n=pthread_create(&tidA,NULL,doit,NULL);  //创建次线次
 if(n!=0)
 std_err("pthread_create");
 n=pthread_create(&tidB,NULL,doit,NULL); //创建第二个次线次
 if(n!=0)
 std_err("pthread_createB");
 n=pthread_join(tidA,NULL);
 if(n!=0)
 std_err("pthread_join");
 n=pthread_join(tidB,NULL);
 if(n!=0)
 std_err("pthread_joinB");
 return 0;
}

栗子呢是来自unix网络编程p554,我不会,就照着写,当然比他那个好看一些。栗子的结果为也上一张图片巴。在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值