linux 读写锁

特性:
读写锁也叫共享——排他锁,因为有3种状态, 所以可以有更高的并行性。使用mutex,它的状态要么处于锁住和未锁状态,只有一个线程可以上锁。而读写锁有更多的状态:在读状态锁住,在写状态锁住,未锁住。只有一个线程可以获得写锁,多个线程可以同时获得读锁。
• 当读写锁是写加锁状态时, 在这个锁被解锁之前, 所有试图对这个锁加锁的线程都会被阻塞。
• 当读写锁在读加锁状态时, 所有试图以读模式对它进行加锁的线程都可以得到访问权, 但是如果线程希望以写模式对此锁进行加锁, 它必须阻塞知道所有的线程释放锁。
• 通常, 当读写锁处于读模式锁住状态时, 如果有另外线程试图以写模式加锁, 读写锁通常会阻塞随后的读模式锁请求, 这样可以避免读模式锁长期占用, 而等待的写模式锁请求长期阻塞。

适用性:
读写锁适合读比写频繁情形。读写锁和互斥量一样也需要在使用前初始化,在释放他们内存的时候销毁。

初始化和销毁:
    int pthread_rwlock_init(pthread_rwlock_t *restrict rwlock, const pthread_rwlockattr_t *restrict attr); 
int pthread_rwlock_destroy(pthread_rwlock_t *restrict rwlock);
一个读写锁可以调用pthread_rwlock_init来初始化,我们可以传递NULL作为attr的参数,这样会使用读写锁的默认属性。我们可以调用pthread_rwlock_destroy来清理,销毁它所占的内存空间。

读和写:
    int pthread_rwlock_rdlock(pthread_rwlock_t *rwlock);  
int pthread_rwlock_wrlock(pthread_rwlock_t *rwlock);
实现上可能会对读写锁中读模式的锁锁住次数有一定的限制,所以我们需要检查返回值,以确定是否成功。而其他的两个函数会返回错误,但是只要我们的锁设计的恰当,我们可以不必做检查。

非阻塞的函数为:
    int pthread_rwlock_tryrdlock(pthread_rwlock_t *rwlock);  
int pthread_rwlock_trywrlock(pthread_rwlock_t *rwlock);
当锁成功获取时,返回0,否则返回EBUSY。这两个函数可以避免死锁。
如果针对未初始化的读写锁调用进行读写操作,则结果是不确定的。

释放:
    int pthread_rwlock_unlock(pthread_rwlock_t *rwlock);
用来释放在 rwlock 引用的读写锁对象中持有的锁。
如果调用线程未持有读写锁 rwlock,或者针对未初始化的读写锁调用该函数,则结果是不确定的。

例子:
#define   _XOPEN_SOURCE   500  
#include <pthread.h>
#define PTHREAD_RWLOCK_INITIALIZER_READ_PREF { {0, 0}, 0, NULL, NULL, NULL, PTHREAD_RWLOCK_PREFER_READER_NP, PTHREAD_PROCESS_PRIVATE }

static pthread_rwlock_t a = PTHREAD_RWLOCK_INITIALIZER;

void *route_3 (void *p)
{
sleep(2);
printf("locking 3 = %d\n", pthread_rwlock_rdlock(&a));
pause();
return NULL;
}

void *route_2 (void *p)
{
sleep(1);
printf("locking 2 = %d\n", pthread_rwlock_wrlock(&a));
pause();
return NULL;
}

void *route_1 (void *p)
{
printf("locking 1 = %d\n", pthread_rwlock_rdlock(&a));
pause();
return NULL;
}

main()
{
pthread_t t1, t2, t3;
pthread_create(&t1, NULL, route_1, NULL);
pthread_create(&t2, NULL, route_2, NULL);
pthread_create(&t3, NULL, route_3, NULL);
pthread_join(t1, NULL);
pthread_join(t2, NULL);
pthread_join(t3, NULL);
}



#include <errno.h>
#include <pthread.h>

static pthread_rwlock_t listlock;
static int lockiniterror = 0;
static pthread_once_t lockisinitialized = PTHREAD_ONCE_INIT;

static void ilock(void) {
lockiniterror = pthread_rwlock_init(&listlock, NULL);
}

int initialize_r(void) { /* must be called at least once before using list */
if (pthread_once(&lockisinitialized, ilock))
lockiniterror = EINVAL;
return lockiniterror;
}

int accessdata_r(void) { /* get a nonnegative key if successful */
int error;
int errorkey = 0;
int key;
if (error = pthread_rwlock_wrlock(&listlock)) { /* no write lock, give up */
errno = error;
return -1;
}
key = accessdata();
if (key == -1) {
errorkey = errno;
pthread_rwlock_unlock(&listlock);
errno = errorkey;
return -1;
}
if (error = pthread_rwlock_unlock(&listlock)) {
errno = error;
return -1;
}
return key;
}

int adddata_r(data_t data) { /* allocate a node on list to hold data */
int error;
if (error = pthread_rwlock_wrlock(&listlock)) { /* no writer lock, give up */
errno = error;
return -1;
}
if (adddata(data) == -1) {
error = errno;
pthread_rwlock_unlock(&listlock);
errno = error;
return -1;
}
if (error = pthread_rwlock_unlock(&listlock)) {
errno = error;
return -1;
}
return 0;
}

int getdata_r(int key, data_t *datap) { /* retrieve node by key */
int error;
if (error = pthread_rwlock_rdlock(&listlock)) { /* no reader lock, give up */
errno = error;
return -1;
}
if (getdata(key, datap) == -1) {
error = errno;
pthread_rwlock_unlock(&listlock);
errno = error;
return -1;
}
if (error = pthread_rwlock_unlock(&listlock)) {
errno = error;
return -1;
}
return 0;
}

int freekey_r(int key) { /* free the key */
int error;
if (error = pthread_rwlock_wrlock(&listlock)) {
errno = error;
return -1;
}
if (freekey(key) == -1) {
error = errno;
pthread_rwlock_unlock(&listlock);
errno = error;
return -1;
}
if (error = pthread_rwlock_unlock(&listlock)) {
errno = error;
return -1;
}
return 0;
}



#include <pthread.h> 
#include <sys/types.h>
#include <sys/stat.h> //文件状态结构
#include <unistd.h>
#include <sys/mman.h> //mmap头文件


#define BSIZE 10
typedef struct {
char buf[BSIZE];
int occupied;
int nextin;
int nextout;
pthread_mutex_t mutex;
pthread_cond_t more;
pthread_cond_t less;
} buffer_t;

char consumer(buffer_t *b)
{
char item;
pthread_mutex_lock(&b->mutex);
while(b->occupied <= 0)
pthread_cond_wait(&b->more, &b->mutex);
assert(b->occupied > 0);
item = b->buf[b->nextout++];
b->nextout %= BSIZE;
b->occupied--;
/* now: either b->occupied > 0 and b->nextout is the index
of the next occupied slot in the buffer, or
b->occupied == 0 and b->nextout is the index of the next
(empty) slot that will be filled by a producer (such as
使用条件变量
120 多线程编程指南• 2006年10月
示例4–13 生成方和使用者问题:使用者(续)
b->nextout == b->nextin) */
pthread_cond_signal(&b->less);
pthread_mutex_unlock(&b->mutex);
return(item);
}

void producer(buffer_t *b, char item)
{
pthread_mutex_lock(&b->mutex);
while (b->occupied >= BSIZE)
pthread_cond_wait(&b->less, &b->mutex);
assert(b->occupied < BSIZE);
b->buf[b->nextin++] = item;
b->nextin %= BSIZE;
b->occupied++;
/* now: either b->occupied < BSIZE and b->nextin is the index
of the next empty slot in the buffer, or
b->occupied == BSIZE and b->nextin is the index of the
next (occupied) slot that will be emptied by a consumer
(such as b->nextin == b->nextout) */
pthread_cond_signal(&b->more);
pthread_mutex_unlock(&b->mutex);
}

void producer_driver(buffer_t *b) {
int item;
while (1) {
item = getchar();
if (item == EOF) {
producer(b, ‘\0’);
break;
} else
producer(b, (char)item);
}

return 0
}

void consumer_driver(buffer_t *b) {
char item;

while (1) {
if ((item = consumer(b)) == ’\0’)
break;
putchar(item);
}
}

int main() {
int zfd;
buffer_t *buffer;

pthread_mutexattr_t mattr;
pthread_condattr_t cvattr_less, cvattr_more;

zfd = open("/dev/zero", O_RDWR);
buffer = (buffer_t *)mmap(NULL, sizeof(buffer_t),PROT_READ|PROT_WRITE, MAP_SHARED, zfd, 0);

buffer->occupied = buffer->nextin = buffer->nextout = 0;

pthread_mutex_attr_init(&mattr);
pthread_mutexattr_setpshared(&mattr,PTHREAD_PROCESS_SHARED);
pthread_mutex_init(&buffer->lock, &mattr);

pthread_condattr_init(&cvattr_less);
pthread_condattr_setpshared(&cvattr_less, PTHREAD_PROCESS_SHARED);
pthread_cond_init(&buffer->less, &cvattr_less);

pthread_condattr_init(&cvattr_more);
pthread_condattr_setpshared(&cvattr_more,PTHREAD_PROCESS_SHARED);
pthread_cond_init(&buffer->more, &cvattr_more);

if (fork() == 0)
consumer_driver(buffer);
else
producer_driver(buffer);


}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
读写锁是用于多线程环境下保护共享资源的一种机制。在 Linux 内核中,读写锁的实现是基于 spinlock 和原子操作的。下面我将简单介绍一下 Linux 内核中读写锁的源码实现。 读写锁的定义: ```c typedef struct { raw_rwlock_t raw_lock; } rwlock_t; ``` 其中,raw_rwlock_t 是一个原始读写锁类型,它是由内核提供的一个结构体类型,定义在 include/linux/spinlock_types.h 文件中。 raw_rwlock_t 的定义: ```c typedef struct { arch_rwlock_t raw_lock; } raw_rwlock_t; typedef struct { unsigned int lock; } arch_rwlock_t; ``` 其中,arch_rwlock_t 是一个体系结构相关的原始读写锁类型,它的实现由不同的处理器架构提供。 下面是 x86_64 架构下的 arch_rwlock_t 实现: ```c struct __arch_rwlock { unsigned int lock; }; typedef struct __arch_rwlock arch_rwlock_t; ``` 可以看到,在 x86_64 架构下,arch_rwlock_t 只包含一个 unsigned int 类型的 lock 成员变量,用于存储锁状态。 读写锁的初始化: ```c void rwlock_init(rwlock_t *lock) { raw_spin_lock_init(&lock->raw_lock.spinlock); atomic_long_set(&lock->raw_lock.rw_sem, 0); } ``` 其中,raw_spin_lock_init() 用于初始化写锁,atomic_long_set() 用于初始化读计数器。 读锁的获取: ```c void read_lock(rwlock_t *lock) { while (1) { long count = atomic_long_read(&lock->raw_lock.rw_sem); if (count >= 0) { if (atomic_long_cmpxchg(&lock->raw_lock.rw_sem, count, count + 1) == count) { break; } } else { cpu_relax(); } } raw_spin_lock(&lock->raw_lock.spinlock); } ``` 其中,atomic_long_read() 用于读取读计数器的值,如果值大于等于 0,则表示读锁可用,此时使用 atomic_long_cmpxchg() 原子操作来增加读计数器并获取读锁;如果值小于 0,则表示有写锁在使用,此时使用 cpu_relax() 函数等待写锁释放。 读锁的释放: ```c void read_unlock(rwlock_t *lock) { raw_spin_unlock(&lock->raw_lock.spinlock); atomic_long_dec(&lock->raw_lock.rw_sem); } ``` 其中,raw_spin_unlock() 用于释放写锁,atomic_long_dec() 用于减少读计数器的值。 写锁的获取: ```c void write_lock(rwlock_t *lock) { raw_spin_lock(&lock->raw_lock.spinlock); while (1) { long count = atomic_long_read(&lock->raw_lock.rw_sem); if (count == 0) { if (atomic_long_cmpxchg(&lock->raw_lock.rw_sem, 0, -1) == 0) { break; } } else { cpu_relax(); } } } ``` 其中,raw_spin_lock() 用于获取写锁,atomic_long_read() 用于读取读计数器的值,如果值等于 0,则表示读锁未被使用,此时使用 atomic_long_cmpxchg() 原子操作将读计数器的值修改为 -1 并获取写锁;如果值大于 0,则表示有读锁在使用,此时使用 cpu_relax() 函数等待读锁释放。 写锁的释放: ```c void write_unlock(rwlock_t *lock) { atomic_long_set(&lock->raw_lock.rw_sem, 0); raw_spin_unlock(&lock->raw_lock.spinlock); } ``` 其中,atomic_long_set() 用于将读计数器的值设为 0,raw_spin_unlock() 用于释放写锁。 以上就是 Linux 内核中读写锁的源码实现。值得注意的是,在多处理器环境下,读写锁的实现可能会涉及到更复杂的机制,例如写者优先等待、读者优先等待等。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值