Linux如何实现读写锁rwlock

2023-04-12 08:32:00 linux 读写 如何实现

.

Linux实现读写锁rwlock的方法有很多种,这里介绍一种基于信号量实现的方法。

首先,定义一个信号量:

typedef struct rwlock_t {

semaphore_t lock;

semaphore_t num_readers;

} rwlock_t;

初始化信号量:

void rwlock_init(rwlock_t *lock) {

lock->lock = 1;

lock->num_readers = 0;

}

读锁定:

void rwlock_rdlock(rwlock_t *lock) {

while (test_and_set(&lock->lock)) {

;

}

lock->num_readers++;

lock->lock = 0;

}

写锁定:

void rwlock_wrlock(rwlock_t *lock) {

while (test_and_set(&lock->lock)) {

;

}

while (lock->num_readers != 0) {

lock->lock = 0;

while (test_and_set(&lock->lock)) {

;

}

}

}

读解锁:

void rwlock_rdunlock(rwlock_t *lock) {

lock->num_readers--;

if (lock->num_readers == 0) {

lock->lock = 0;

}

}

写解锁:

void rwlock_wrunlock(rwlock_t *lock) {

lock->lock = 0;

}

相关文章