读写锁是一种用于控制对共享资源的访问的同步机制,它允许多个线程同时对共享资源进行读取访问,但在有写操作时,必须独占资源,防止其他线程进行读或写操作。这种锁通常用于提高读操作的并发性能,因为多个线程可以同时读取共享资源,但在写操作时需要独占资源,以确保数据的一致性和完整性。
读写锁通常分为读锁和写锁两种状态:
- 读锁(共享锁):允许多个线程同时持有,用于读取共享资源。
- 写锁(独占锁):在有写操作时独占资源,防止其他线程进行读或写操作。
读写锁使用示例:
#include <stdio.h>
#include <pthread.h>
pthread_rwlock_t rwlock; // 读写锁
int shared_data = 0; // 共享资源
// 读线程函数
void *reader(void *arg) {
pthread_rwlock_rdlock(&rwlock); // 获取读锁
printf("Reader %ld read shared data: %d\n", (long)arg, shared_data);
pthread_rwlock_unlock(&rwlock); // 释放读锁
return NULL;
}
// 写线程函数
void *writer(void *arg) {
pthread_rwlock_wrlock(&rwlock); // 获取写锁
shared_data++; // 修改共享资源
printf("Writer %ld modified shared data to: %d\n", (long)arg, shared_data);
pthread_rwlock_unlock(&rwlock); // 释放写锁
return NULL;
}
int main() {
pthread_t readers[5], writers[2];
pthread_rwlock_init(&rwlock, NULL); // 初始化读写锁
// 创建读线程
for (long i = 0; i < 5; i++) {
pthread_create(&readers[i], NULL, reader, (void *)i);
}
// 创建写线程
for (long i = 0; i < 2; i++) {
pthread_create(&writers[i], NULL, writer, (void *)i);
}
// 等待所有线程结束
for (int i = 0; i < 5; i++) {
pthread_join(readers[i], NULL);
}
for (int i = 0; i < 2; i++) {
pthread_join(writers[i], NULL);
}
// 销毁读写锁
pthread_rwlock_destroy(&rwlock);
return 0;
}
编译运行我们可以得到类似如下的结果:
# ./a.out
Reader 0 read shared data: 0
Reader 1 read shared data: 0
Reader 3 read shared data: 0
Reader 4 read shared data: 0
Reader 2 read shared data: 0
Writer 0 modified shared data to: 1
Writer 1 modified shared data to: 2