读写锁的创建和销毁
#include<pthread.h>
int pthread_rwlock_init(pthread_rwlock_t *restrict rwlock,
const pthread_rwlockattr_t *restrict attr);
int pthread_rwlock_destroy(pthread_rwlock_t *rwlock);
返回值:成功返回0,否则返回错误编号
读写锁的数据类型:pthread_rwlock_t
参数:
rwlock:读写锁
attr:读写锁属性
读写锁加锁和解锁
#include<pthread.h>
加读锁:
int pthread_rwlock_rdlock(pthread_rwlock_t *rwlock);
加写锁:
int pthread_rwlock_wrlock(pthread_rwlock_t *rwlock);
释放锁:
int pthread_rwlock_unlock(pthread_rwlock_t *rwlock);
返回值:成功返回0,否则返回错误编号
参数:
rwlock:读写锁
示例查看
#include <cstdlib>
#include<iostream>
#include<pthread.h>
#include<string.h>
using namespace std;
//定义读写锁
pthread_rwlock_t rwlock;
int main(int argc,char* argv[])
{
//读写锁的初始化
if(argc<3)
{
//argv[0]表示该可执行文件的路径
cout<<"-usage:"<<argv[0]<<"[r|w] [r|w]"<<endl;
exit(1);
}
pthread_rwlock_init(&rwlock,NULL);
if(!strcmp("r",argv[1]))
{
//加读锁
if(pthread_rwlock_rdlock(&rwlock)!=0)
{
cout<<"first read lock failure"<<endl;
}
else
{
cout<<"first read lock success"<<endl;
}
}
else if(!strcmp("w",argv[1]))
{
//加写锁
if(pthread_rwlock_wrlock(&rwlock)!=0)
{
cout<<"first write lock failure"<<endl;
}
else
{
cout<<"first write lock success"<<endl;
}
}
if(!strcmp("r",argv[2]))
{
//加读锁
if(pthread_rwlock_rdlock(&rwlock)!=0)
{
cout<<"second read lock failure"<<endl;
}
else
{
cout<<"second write lock success"<<endl;
}
}
else if(!strcmp("w",argv[2]))
{
//加写锁
if(pthread_rwlock_wrlock(&rwlock)!=0)
{
cout<<"second write lock failure"<<endl;
}
else
{
cout<<"second write lock success"<<endl;
}
}
pthread_rwlock_unlock(&rwlock);
pthread_rwlock_unlock(&rwlock);
//r r (成功,成功)
//r w (成功,阻塞)
//w r (成功,失败)
//w w (成功,失败)
/*
读写锁特性:
读和读:不排斥
读和写:排斥
写和读:排斥
*/
return 0;
}