读写锁
与互斥量类似,但读写锁允许更高的并行性。其特性为:写独占,读共享。
读写锁状态:
一把读写锁具备三种状态:
1. 读模式下加锁状态 (读锁)
2. 写模式下加锁状态 (写锁)
3. 不加锁状态
读写锁特性:
1.读写锁是“写模式加锁”时, 解锁前,所有对该锁加锁的线程都会被阻塞。
2.读写锁是“读模式加锁”时, 如果线程以读模式对其加锁会成功;如果线程以写模式加锁会阻塞。
3.读写锁是“读模式加锁”时, 既有试图以写模式加锁的线程,也有试图以读模式加锁的线程。那么读写锁会阻塞随后的读模式锁请求。优先满足写模式锁。读锁、写锁并行阻塞,写锁优先级高
读写锁也叫共享-独占锁。当读写锁以读模式锁住时,它是以共享模式锁住的;当它以写模式锁住时,它是以独占模式锁住的。写独占、读共享。
读写锁非常适合于对数据结构读的次数远大于写的情况。
静态初始化
pthread_rwlock_t rwlock = PTHREAD_RWLOCK_INITIALIZER;
动态初始化
pthread_rwlock_init(&rw_lock,NULL);
读写锁示例
看如下示例,同时有多个线程对同一全局数据读、写操作。
#include<stdlib.h>
#include<stdio.h>
#include<unistd.h>
#include<pthread.h>
int counter=0;
pthread_rwlock_t rwlock=PTHREAD_RWLOCK_INITIALIZER;
/* 3个线程不定时写同一全局资源,5个线程不定时读同一全局资源 */
void *th_write(void *arg)
{
int t, i = *(int*)arg;
while (1) {
pthread_rwlock_wrlock(&rwlock);//加写锁
t = counter;
sleep(rand()%2);
printf("=======write %d: %lu: counter=%d ++counter=%d\n", i, pthread_self(), t, ++counter);
pthread_rwlock_unlock(&rwlock);
sleep(rand()%2);
}
return NULL;
}
void *th_read(void *arg)
{
int i = *(int*)arg;
while (1) {
pthread_rwlock_rdlock(&rwlock);//加读锁
printf("----------------------------read %d: %lu: %d\n", i, pthread_self(), counter);
pthread_rwlock_unlock(&rwlock);
sleep(rand()%2);
}
return NULL;
}
int main(void)
{
int i;
pthread_t tid[8];
//pthread_rwlock_init(&rwlock, NULL);
for (i = 0; i < 3; i++)
{
pthread_create(&tid[i], NULL, th_write, (void *)&i);
usleep(10);//如果没有的话,我的传参打印都是0,加个usleep
}
for (i = 3; i < 8; i++)
{
pthread_create(&tid[i], NULL, th_read, (void *)&i);
usleep(10);
}
for (i = 0; i < 8; i++)
pthread_join(tid[i], NULL);
pthread_rwlock_destroy(&rwlock);
return 0;
}
部分编译输出:
=======write 0: 140516228192000: counter=0 ++counter=1
----------------------------read 3: 140516203013888: 1
----------------------------read 4: 140516194621184: 1
----------------------------read 5: 140516186228480: 1
----------------------------read 6: 140516177835776: 1
----------------------------read 7: 140516169443072: 1
=======write 1: 140516219799296: counter=1 ++counter=2
=======write 2: 140516211406592: counter=2 ++counter=3
----------------------------read 6: 140516177835776: 3
----------------------------read 3: 140516203013888: 3
----------------------------read 5: 140516186228480: 3
----------------------------read 4: 140516194621184: 3
----------------------------read 7: 140516169443072: 3
=======write 1: 140516219799296: counter=3 ++counter=4
----------------------------read 3: 140516203013888: 4
=======write 2: 140516211406592: counter=4 ++counter=5
----------------------------read 3: 140516203013888: 5
----------------------------read 7: 140516169443072: 5
=======write 0: 140516228192000: counter=5 ++counter=6
----------------------------read 5: 140516186228480: 6
----------------------------read 4: 140516194621184: 6
本文深入解析读写锁机制,探讨其在并发控制中的优势及应用场景,尤其适合读操作远超写操作的数据结构,通过示例代码展示读写锁在多线程环境下的使用方法。
292

被折叠的 条评论
为什么被折叠?



