多线程编程 之读写锁
Pthread 是 POSIX threads 的简称,是POSIX的 线程标准 。
1.读写锁机制 :
写者 :写者使用 写锁 ,假设当前没有读者,也没有其它写者,写者马上获得写锁;否则写者将等待,直到没有读者和写者。
读者 :读者使用 读锁 ,假设当前没有写者,读者马上获得读锁;否则读者等待,直到没有写者。
2.读写锁特性 :
同一时刻仅仅有一个线程能够获得写锁,同一时刻能够有多个线程获得读锁。
读写锁出于写锁状态时,全部试图对读写锁加锁的线程,无论是读者试图加读锁,还是写者试图加写锁,都会被堵塞。
读写锁处于读锁状态时,有写者试图加写锁时,之后的其它线程的读锁请求会被堵塞,以避免写者长时间的不写锁。
3.读写锁基本函数 :
# include<pthread.h>
读写锁初始化:
int pthread_rwlock_init ( pthread_rwlock_t * rwlock,
const pthread_rwlockattr_t * attr );
该函数第一个參数为读写锁指针,第二个參数为读写锁属性指针。函数按读写锁属性对读写锁进行初始化。
加读锁:
int pthread_rwlock_rdlock ( pthread_rwlock_t *rwlock );
该函数參数为读写锁指针。函数用于对读写锁加读锁。
加写锁:
int pthread_rwlock_wrlock ( pthread_rwlock_t *rwlock );
该函数參数为读写锁指针。函数用于对读写锁加写锁。
释放读写锁:
int pthread_rwlock_unlock ( pthread_rwlock_t *rwlock );
该函数參数为读写锁指针。函数用于释放读写锁,包含读锁与写锁。
销毁读写锁:
int pthread_rwlock_destroy ( pthread_rwlock_t *rwlock );
该函数參数为读写锁指针。函数用于销毁读写锁。
4.牛刀小试 :
演示样例使用读写锁,对共享资源data进行读写同步,线程readerM,readerN为读者线程,线程writerA,writerB为写者线程。
#include <iostream>
#include <cstdlib>
#include <unistd.h>
#include <pthread.h>
using namespace std;
struct{
pthread_rwlock_t rwlock;
int product;
}sharedData = {PTHREAD_RWLOCK_INITIALIZER, 0};
void * produce(void *ptr)
{
for (int i = 0; i < 5; ++i)
{
pthread_rwlock_wrlock(&sharedData.rwlock);
sharedData.product = i;
pthread_rwlock_unlock(&sharedData.rwlock);
sleep(1);
}
}
void * consume1(void *ptr)
{
for (int i = 0; i < 5;)
{
pthread_rwlock_rdlock(&sharedData.rwlock);
cout<<"consume1:"<<sharedData.product<<endl;
pthread_rwlock_unlock(&sharedData.rwlock);
++i;
sleep(1);
}
}
void * consume2(void *ptr)
{
for (int i = 0; i < 5;)
{
pthread_rwlock_rdlock(&sharedData.rwlock);
cout<<"consume2:"<<sharedData.product<<endl;
pthread_rwlock_unlock(&sharedData.rwlock);
++i;
sleep(1);
}
}
int main()
{
pthread_t tid1, tid2, tid3;
pthread_create(&tid1, NULL, produce, NULL);
pthread_create(&tid2, NULL, consume1, NULL);
pthread_create(&tid3, NULL, consume2, NULL);
void *retVal;
pthread_join(tid1, &retVal);
pthread_join(tid2, &retVal);
pthread_join(tid3, &retVal);
return 0;
}
如果把consume1的解锁注释掉,如下:
void * consume1(void *ptr)
{
for (int i = 0; i < 5;)
{
pthread_rwlock_rdlock(&sharedData.rwlock);
cout<<"consume1:"<<sharedData.product<<endl;
//pthread_rwlock_unlock(&sharedData.rwlock);
++i;
sleep(1);
}
}