linux 读者写着问题 c++

用读写锁解决

namespace std;
pthread_rwlock_t rwlock;
int add=0;
void *read(void*param){
   string name=*((string*)param);
   while(true){
      if(add>=30){
         break;
      }
      pthread_rwlock_rdlock(&rwlock);
      cout<<name<<" read book"<<endl;
      sleep(1);
      cout<<name<<" leave"<<endl;
      pthread_rwlock_unlock(&rwlock);
      sleep(1);
   }
}
void *write(void*param){
   string name=*((string*)param);
   while(true){
     if(add>=30){
       break;
     }
     pthread_rwlock_wrlock(&rwlock);
     cout<<name<<" write book"<<endl;
     sleep(1);
     cout<<name<<" leave"<<endl;
     add++;
     cout<<add<<endl;
     pthread_rwlock_unlock(&rwlock);
     sleep(2);
   }
}
int main(){
   string name[5]={"write1","write2","read1","read2","read3"};
   pthread_t write1,write2,read1,read2,read3;
   pthread_rwlock_init(&rwlock,NULL);
   pthread_create(&write1,NULL,write,&name[0]);
   pthread_create(&write2,NULL,write,&name[1]);
   pthread_create(&read1,NULL,read,&name[2]);
   pthread_create(&read2,NULL,read,&name[3]);
   pthread_create(&read3,NULL,read,&name[4]);
   pthread_join(write1,NULL);
   pthread_join(write2,NULL);
   pthread_join(read1,NULL);
   pthread_join(read2,NULL);
   pthread_join(read3,NULL);
   return 0;
}

g++ -o name name.cpp -pthread


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值