作用
互斥锁在任一时刻只允许有一个线程访问关键资源, 不管是读取或写操作.
读写锁将互斥锁的功能一分为二, 分成读与写两种操作, 当进行读取操作时允许多个线程同时访问, 当进行写操作时只允许一个一个线程访问
基本函数
#include <pthread.h>
int pthread_rwlock_rdlock(pthread_rwlock_t *rwptr);
int pthread_rwlock_wdlock(pthread_rwlock_t *rwptr);
int pthread_rwlock_unlock(pthread_rwlock_t *rwptr);
int pthread_rwlock_tryrdlock(pthread_rwlock_t *rwptr);
int pthread_rwlock_trywrlock(pthread_rwlock_t *rwptr);
//初始化
PTHREAD_RWLOCK_INITIALIZER
int pthread_rwlock_init(pthread_rwlock_t *rwptr,const pthread_rwlockattr_t *attr);
int pthread_rwlock_destroy(pthread_rwlock_t *rwptr);
例子
两个线程用读锁读取内容; 两个线程用写锁修改内容
#include "unpipc.h"
#include <pthread.h>
struct {
pthread_rwlock_t rwlock;
char name[20];
int age;
} man = {
PTHREAD_RWLOCK_INITIALIZER,"aman",20
};
void *showinfo(void *arg), *changeinfo(void *);
int main(int argc, char *argv[]){
pthread_t tid1,tid2;
pthread_create(&tid1,NULL,showinfo,NULL);
pthread_create(&tid2,NULL,showinfo,NULL);
pthread_join(tid1,NULL);
pthread_join(tid2,NULL);
pthread_create(&tid1,NULL,changeinfo,NULL);
pthread_create(&tid2,NULL,changeinfo,NULL);
pthread_join(tid1,NULL);
pthread_join(tid2,NULL);
pthread_rwlock_destroy(&man.rwlock);
return 0;
}
void *
showinfo(void *arg){
pthread_rwlock_rdlock(&man.rwlock);
printf("thread %ld: in showinfo
",(long)pthread_self());
printf("name:%s,age:%d
",man.name,man.age);
sleep(3);
printf("thread %ld: out showinfo
",(long)pthread_self());
pthread_rwlock_unlock(&man.rwlock);
return NULL;
}
void *
changeinfo(void *arg){
pthread_rwlock_wrlock(&man.rwlock);
printf("thread %ld: in changeinfo
",(long)pthread_self());
man.age=1;
printf("name:%s,age:%d
",man.name,man.age);
sleep(3);
printf("thread %ld: out changeinfo
",(long)pthread_self());
pthread_rwlock_unlock(&man.rwlock);
return NULL;
}