#include <pthread.h>
#include <stdio.h>
#include <unistd.h>
pthread_rwlock_t lock;
void *write1(void *arg)
{
pthread_rwlock_wrlock(&lock);
puts("write1");
pthread_rwlock_unlock(&lock);
return NULL;
}
void *read1(void *arg)
{
pthread_rwlock_rdlock(&lock);
puts("read1");
sleep(2);
pthread_rwlock_unlock(&lock);
return NULL;
}
void *read2(void *arg)
{
pthread_rwlock_rdlock(&lock);
puts("read2");
pthread_rwlock_unlock(&lock);
return NULL;
}
int main(void)
{
pthread_t th1,th2,th3;
int ret = 0;
ret = pthread_rwlock_init(&lock,NULL);
if( ret != 0 )
{
perror("pthread_rwlock_init");
return -1;
}
ret = pthread_create(&th1,NULL,read1,NULL);
if( ret != 0 )
{
perror("read1 ");
return -2;
}
usleep(2000);
ret = pthread_create(&th2,NULL,write1,NULL);
if( ret != 0 )
{
perror("write1 ");
return -3;
}
usleep(2000);
ret = pthread_create(&th3,NULL,read2,NULL);
if( ret != 0 )
{
perror("read2 ");
return -4;
}
pthread_join(th1,NULL);
pthread_join(th2,NULL);
pthread_join(th3,NULL);
pthread_rwlock_destroy(&lock);
return 0;
}
读写锁特点:
1)多个读者可以同时进行读
2)写者之间必须互斥
3)写者与读者之间互斥
4 ) 写者优先于读者(唤醒时优先考虑写者)
互斥锁特点:
1 ) 一次只能一个线程拥有互斥锁,其他线程只有等待
读写锁实现了互斥锁。