读写锁是一种与互斥量类似的锁,它允许更高的并行性,具有写独占,读共享的特点。读写锁总共有三种状态:
读写锁,所谓读共享写独占是指,加读锁的时候,可以多线程一块读,但是不能写;加写锁的时候,不能读,只有当前线程可以写。并且写优先级高于读。读写锁是一把锁,有上面三种状态。
读写锁也叫做共享-独占锁,当读写锁以读模式锁住时,它是以共享模式锁住的;当它以写模式锁住时,它是以独占模式锁住的,也就是所谓的写独占,读共享。读写锁适用于对数据结构读的次数远大于写的情况,因为多线程加读锁的时候可以同时读,效率更高。
#include <pthread.h>
int pthread_rwlock_destroy(pthread_rwlock_t *rwlock);
int pthread_rwlock_init(pthread_rwlock_t *restrict rwlock, const pthread_rwlockattr_t *restrict attr);
#include <pthread.h>
int pthread_rwlock_rdlock(pthread_rwlock_t *rwlock);
int pthread_rwlock_tryrdlock(pthread_rwlock_t *rwlock);
#include <pthread.h>
int pthread_rwlock_trywrlock(pthread_rwlock_t *rwlock);
int pthread_rwlock_wrlock(pthread_rwlock_t *rwlock);
#include <pthread.h>
int pthread_rwlock_unlock(pthread_rwlock_t *rwlock);
#include <stdio.h>
#include <unistd.h>
#include <pthread.h>
pthread_rwlock_t rwlock = PTHREAD_RWLOCK_INITIALIZER;
int gdata = 100;
void* read_th(void* arg)
{
while(1)
{
pthread_rwlock_rdlock(&rwlock);
printf("read thread: %s, tid: %d, gdata: %d\n", __FUNCTION__, pthread_self(), gdata);
usleep(8000);
pthread_rwlock_unlock(&rwlock);
usleep(6000);
}
}
void* write_th(void* arg)
{
while(1)
{
pthread_rwlock_wrlock(&rwlock);
printf("write thread: %s, tid: %d, gdata: %d\n", __FUNCTION__, pthread_self(), ++gdata);
usleep(8000);
pthread_rwlock_unlock(&rwlock);
usleep(9000);
}
}
int main(int argc, char* argv[])
{
pthread_t tid[6];
for(i = 0; i < 4; i++)
{
pthread_create(&tid[i], NULL, read_th, NULL);
}
for(; i< 6; i++)
{
pthread_join(&tid[i], NULL, write_th, NULL);
}
for(i = 0; i < 6; i++)
{
pthread_join(tid[i], NULL);
}
return 0;
}