相比与互斥锁,读写锁把对临界资源的操作细分为读和写。对于同一资源,当没有写操作时,允许同时读;当有写操作时,读写都被阻塞。
写了个小demo,有两个线程同时对一变量进行写操作,一个线程读取变量。
#include <iostream>
#include <thread>
using namespace std;
int main()
{
int count=0;
pthread_rwlock_t my_rwlock;
pthread_rwlock_init(&my_rwlock, nullptr);
std::thread mythread1([&]{
while(1)
{
if(pthread_rwlock_wrlock(&my_rwlock)==0)
{
count++;
}
else
{
std::cout<<"thread_1 write block"<<std::endl;
}
pthread_rwlock_unlock(&my_rwlock);
this_thread::sleep_for(chrono::milliseconds(100));
}
});
mythread1.detach();
std::thread mythread2([&]{
while(1)
{
if(pthread_rwlock_wrlock(&my_rwlock)==0)
{
count++;
}
else
{
std::cout<<"thread_2 write block"<<std::endl;
}
pthread_rwlock_unlock(&my_rwlock);
this_thread::sleep_for(chrono::milliseconds(100));
}
});
mythread2.detach();
std::thread mythread3([&]{
while(1)
{
pthread_rwlock_rdlock(&my_rwlock);
std::cout<<"thread_3 get count:"<<count<<std::endl;
pthread_rwlock_unlock(&my_rwlock);
this_thread::sleep_for(chrono::milliseconds(100));
}
});
mythread3.join();
return 0;
}