描述
一次只有一个线程可以占有写模式的读写锁,但是可以有多个线程同时占有读模式的读写锁,正是因为这个特性,当读写锁是写加锁状态时,在这个锁被解锁之前, 所有试图对这个锁加锁的线程都会被阻塞。
通常,当读写锁处于读模式锁住状态时,如果有另外线程试图以写模式加锁,读写锁通常会阻塞随后的读模式锁请求, 这样可以避免读模式锁长期占用, 而等待的写模式锁请求长期阻塞。
相关知识
初始化操作:
pthread_rwlock_init(
pthread_rwlock_t *restrict rwlock,
const pthread_rwlockattr_t *restrict attr
);
销毁锁操作:
pthread_rwlock_destroy(pthread_rwlock_t *rwlock);
成功则返回0,出错则返回错误编号
pthread_rwlock_rdlock(pthread_rwlock_t *rwlock); pthread_rwlock_wrlock(pthread_rwlock_t *rwlock); pthread_rwlock_unlock(pthread_rwlock_t *rwlock);
这3个函数分别实现获取读锁, 获取写锁和释放锁的操作
实现代码
#include <errno.h>
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <bits/pthreadtypes.h>
static pthread_rwlock_t rwlock; //读写锁对象
int count = 0;
void *thread_function_read(void *arg)
{
while(1)
{
pthread_rwlock_rdlock(&rwlock);
printf("***%ld, read count %d\n", pthread_self(), count);
sleep(1);
pthread_rwlock_unlock(&rwlock);
usleep(100);
}
return NULL;
}
void *thread_function_write(void *arg)
{
while(1)
{
pthread_rwlock_wrlock(&rwlock);
count++;
printf("***%ld, write count %d\n", pthread_self(), count);
sleep(1);
pthread_rwlock_unlock(&rwlock);
usleep(100);
}
return NULL;
}
int main(int argc, char *argv[])
{
pthread_t rpthread1, rpthread2, wpthread;
pthread_rwlock_init(&rwlock,NULL);
pthread_create(&rpthread1, NULL, thread_function_read, NULL);
pthread_create(&rpthread2, NULL, thread_function_read, NULL);
pthread_create(&wpthread, NULL, thread_function_write, NULL);
pthread_join(rpthread1, NULL);
pthread_join(rpthread2, NULL);
pthread_join(wpthread, NULL);
pthread_rwlock_destroy(&rwlock);
return 0;
}
运行结果
***139633593894656, read count 0
***139633585501952, read count 0
***139633442891520, write count 1
***139633593894656, read count 1
***139633585501952, read count 1
.
.
.
最后
- 由于博主水平有限,难免有疏漏之处,欢迎读者批评指正!