【Linux】—— Linux读写者模型

读写者模型

读写锁

在编写多线程的时候,有一种情况是十分常见的。那就是,有些公共数据修改的机会比较少。相比较改写,它们读的机会反而高的多。通常而言,在读的过程中,往往伴随着查找的操作,中间耗时很长。给这种代码段加锁,会极大地降低我们程序的效率。那么有没有一种方法,可以专门处理这种多读少写的情况呢? 有,那就是读写锁

读写锁行为

读写锁接口

设置读写优先

读写优先

初始化

初始化

销毁

销毁

加锁和解锁

加锁解锁

读写者模型源码展示

#include <iostream>
#include <pthread.h>
#include <unistd.h>

using namespace std;
int data = 0;
pthread_rwlock_t rw;

void* reader(void* arg)
{
    for(;;){
        pthread_rwlock_rdlock(&rw);
        cout << "reader read done: " << data << endl;
        pthread_rwlock_unlock(&rw);
        usleep(100);
    }
}

void* writer(void* arg)
{
    for(;;){
        pthread_rwlock_wrlock(&rw);
        cout << "writer write done : "<< ++data << endl;
        pthread_rwlock_unlock(&rw);
        usleep(90);
    }
}


int main()
{
    pthread_rwlock_init(&rw,NULL);
    pthread_t r[5],w;
    for(int i = 0;i < 5; ++i){
         pthread_create(&r[i],NULL,reader,NULL);
    }
    pthread_create(&w,NULL,writer,NULL);

    for(int i = 0;i < 5; ++i){
         pthread_join(r[i],NULL);
    }
    pthread_join(w,NULL);
    pthread_rwlock_destroy(&rw);
    return 0;
}

  • Makefile
rw:rw.cc
	g++ -std=c++11 -o $@ $^ -lpthread
.PHONY:clean
clean:
	rm -f rw
发布了167 篇原创文章 · 获赞 175 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/chenxiyuehh/article/details/97615289