Linux_c:多线程之读写锁

读写锁

概念

读写锁与互斥量类似,不过读写锁有更高的并行性。互斥量要么加锁要么不加锁,而且同一时刻只允许一个线程对其加锁。对于一个变量的读取,完全可以让多个线程同时进行操作。

pthread_rwlock_t nwlock

读写锁有三种状态,读模式下加锁,写模式下加锁,不加锁。一次只有一个线程可以占有写模式下的读写锁,但是多个线程可以同时占有读模式的读写锁。

读写锁在写加锁状态时,在它被解锁之前,所有试图对这个锁加锁的线程都会阻塞。读写锁在读加锁状态时,所有试图以读模式对其加锁的线程都会获得访问权,但是如果线程希望以写模式对其加锁,它必须阻塞直到所有的线程释放锁。

当读写锁一读模式加锁时,如果有线程试图以写模式对其加锁,那么读写锁会阻塞随后的读模式锁请求。 这样可以避免读锁长期占用,而写锁达不到请求。

读写锁非常适合对数据结构读次数大于写次敌的程序,当它以读模式锁住时,是以共享的方式锁住的;当它以写模式谈住时,是以独占的模式谈住的。

读写锁的初始化和销毁

读写锁在使用之前必须初始化

int pthread_rwlock_init(pthread_rwlock_t *restrict rwlock, const pthread_rwlockattr_t *restrict attz);

使用完需要销毁

int pthread_rwlock_destroy(pthread_rwlock_t *rwlock);

成功返回0﹐共败返回错误码

代码

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <pthread.h>

//全局变量 锁 / 值
pthread_rwlock_t rwlock;
int i = 1;

//线程1
void *thread_func1(void *arg){

        pthread_rwlock_rdlock(&rwlock); //读锁 1
      //pthread_rwlock_wrlock(&rwlock); //写锁 2

        printf("thread 1 : i = %d \n", i);
        sleep(5);
        printf("thread 1 over \n");

        pthread_rwlock_unlock(&rwlock);


        return (void *)1;

}



//线程2
void *thread_func2(void *arg){

        pthread_rwlock_rdlock(&rwlock); //读锁 1
      //pthread_rwlock_wrlock(&rwlock); //写锁 2

        printf("thread 2 : i = %d \n", i);
        sleep(5);
        printf("thread 2 over \n");

        pthread_rwlock_unlock(&rwlock);


        return (void *)2;

}

int main(){


        pthread_t tid1, tid2;
        int err;

        // 初始化读写锁
        err = pthread_rwlock_init(&rwlock, NULL);
        if(!err){
                printf("init thread_rwlock failed \n");
                return ;
        }

        //创建新线程1,失败直接退出
        err = pthread_create(&tid1, NULL, thread_func1, NULL);
        if(err){
                printf("new thread 1 create failed \n");
                return ;
        }

        //创建新线程2,失败直接退出
        err = pthread_create(&tid2, NULL, thread_func2, NULL);
        if(err){
                printf("new thread 2 create failed \n");
                return ;
        }

        //等待线程1,2运行完再结束
        pthread_join(tid1, NULL);
        pthread_join(tid2, NULL);

        //销毁锁
        pthread_rwlock_destroy(&rwlock);

        return 0;
}

运行结果

上述代码直接运行结果

运行结果1:

thread 1 : i = 1 
thread 2 : i = 1 
thread 2 over 
thread 1 over 

若将 1 注释, 2 去掉注释

运行结果2:

thread 1 : i = 1 
thread 1 over 
thread 2 : i = 1 
thread 2 over 

读写锁一起使用代码

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>

pthread_rwlock_t rwlock;
int num = 0;

void *func1(void *arg){

        while(1){
                if(num%2 == 0){
                        pthread_rwlock_wrlock(&rwlock);
                        num ++;
                        printf("thread 1 write: num = %d \n", num);
                        pthread_rwlock_unlock(&rwlock);
                        printf("\nthread 1 write over \n\n");
                        sleep(2);
                }else{
                        pthread_rwlock_rdlock(&rwlock);
                        printf("thread 1 read : num = %d \n", num);
                        pthread_rwlock_unlock(&rwlock);
                        printf("thread 1 read over \n");
                        sleep(2);
                }

                if(num > 10) return ;

        }
}


void *func2(void *arg){

        while(1){
                if(num%2 == 1){
                        pthread_rwlock_wrlock(&rwlock);
                        num ++;
                        printf("thread 2 write : num = %d \n", num);

                        pthread_rwlock_unlock(&rwlock);
                        printf("\nthread 2 write over \n\n");
                        sleep(2);
                }else{
                        pthread_rwlock_rdlock(&rwlock);
                        printf("thread 2 read : num is %d \n", num);
                        pthread_rwlock_unlock(&rwlock);
                        printf("thread 2 read over \n");
                        sleep(2);

                }

                if(num > 10) return ;

        }
}



int main(){

        pthread_t tid1, tid2;
        int err;

        err = pthread_rwlock_init(&rwlock, NULL);
        if(err){
                printf("rwlock init failed \n");
        }

        err = pthread_create(&tid1, NULL, func1, NULL);
        if(err){
                printf("thread 1 create failed \n");
                return ;
        }

        err = pthread_create(&tid2, NULL, func2, NULL);
        if(err){
                printf("thread 2 create failed \n");
                return ;
        }

        pthread_join(tid1, NULL);
        pthread_join(tid2, NULL);

        return 0;
}


读写锁两个奇偶数

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>

pthread_rwlock_t rwlock;
int num = 0;

void *func1(void *arg){
  
        while(1){
                if(num%2 == 0){
                        pthread_rwlock_wrlock(&rwlock);
                        num ++;
                        printf("thread 1 : num = %d \n", num);
                        pthread_rwlock_unlock(&rwlock);

                        sleep(2);
                }

                if(num > 10) return ;

        }
}

void *func2(void *arg){

        while(1){
                if(num%2 == 1){
                        pthread_rwlock_wrlock(&rwlock);
                        num ++;
                        printf("thread 2 : num = %d \n", num);

                        pthread_rwlock_unlock(&rwlock);
                        sleep(2);
                }

                if(num > 10) return ;

        }
}





int main(){

        pthread_t tid1, tid2;
        int err;

        err = pthread_rwlock_init(&rwlock, NULL);
        if(err){
                printf("rwlock init failed \n");
        }
    
    
        err = pthread_rwlock_init(&rwlock, NULL);
        if(err){
                printf("rwlock init failed \n");
        }

        err = pthread_create(&tid1, NULL, func1, NULL);
        if(err){
                printf("thread 1 create failed \n");
                return ;
        }

        err = pthread_create(&tid2, NULL, func2, NULL);
        if(err){
                printf("thread 2 create failed \n");
                return ;
        }

        pthread_join(tid1, NULL);
        pthread_join(tid2, NULL);

        return 0;
}


运行结果

thread 1 : num = 1 
thread 2 : num = 2 
thread 1 : num = 3 
thread 2 : num = 4 
thread 1 : num = 5 
thread 2 : num = 6 
thread 1 : num = 7 
thread 2 : num = 8 
thread 1 : num = 9 
thread 2 : num = 10 
thread 1 : num = 11 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
同步概念 所谓同步,即同时起步,协调一致。不同的对象,对“同步”的理解方式略有不同。如,设备同步,是指在两个设备之间规定一个共同的时间参考;数据库同步,是指让两个或多个数据库内容保持一致,或者按需要部分保持一致;文件同步,是指让两个或多个文件夹里的文件保持一致。等等 而,编程中、通信中所说的同步与生活中大家印象中的同步概念略有差异。“同”字应是指协同、协助、互相配合。主旨在协同步调,按预定的先后次序运行。 线程同步 同步即协同步调,按预定的先后次序运行。 线程同步,指一个线程发出某一功能调用时,在没有得到结果之前,该调用不返回。同时其它线程为保证数据一致性,不能调用该功能。 举例1: 银行存款 5000。柜台,折:取3000;提款机,卡:取 3000。剩余:2000 举例2: 内存中100字节,线程T1欲填入全1, 线程T2欲填入全0。但如果T1执行了50个字节失去cpu,T2执行,会将T1写过的内容覆盖。当T1再次获得cpu继续 从失去cpu的位置向后写入1,当执行结束,内存中的100字节,既不是全1,也不是全0。 产生的现象叫做“与时间有关的错误”(time related)。为了避免这种数据混乱,线程需要同步。 “同步”的目的,是为了避免数据混乱,解决与时间有关的错误。实际上,不仅线程需要同步,进程间、信号间等等都需要同步机制。 因此,所有“多个控制流,共同操作一个共享资源”的情况,都需要同步。 数据混乱原因: 1. 资源共享(独享资源则不会) 2. 调度随机(意味着数据访问会出现竞争) 3. 线程间缺乏必要的同步机制。 以上3点中,前两点不能改变,欲提高效率,传递数据,资源必须共享。只要共享资源,就一定会出现竞争。只要存在竞争关系,数据就很容易出现混乱。 所以只能从第三点着手解决。使多个线程在访问共享资源的时候,出现互斥。 互斥量mutex Linux中提供一把互斥mutex(也称之为互斥量)。 每个线程在对资源操作前都尝试先加,成功加才能操作,操作结束解。 资源还是共享的,线程间也还是竞争的, 但通过“”就将资源的访问变成互斥操作,而后与时间有关的错误也不会再产生了。 但,应注意:同一时刻,只能有一个线程持有该。 当A线程对某个全局变量访问,B在访问前尝试加,拿不到,B阻塞。C线程不去加,而直接访问该全局变量,依然能够访问,但会出现数据混乱。 所以,互斥实质上是操作系统提供的一把“建议”(又称“协同”),建议程序中有多线程访问共享资源的时候使用该机制。但,并没有强制限定。 因此,即使有了mutex,如果有线程不按规则来访问数据,依然会造成数据混乱。 主要应用函数: pthread_mutex_init函数 pthread_mutex_destroy函数 pthread_mutex_lock函数 pthread_mutex_trylock函数 pthread_mutex_unlock函数 以上5个函数的返回值都是:成功返回0, 失败返回错误号。 pthread_mutex_t 类型,其本质是一个结构体。为简化理解,应用时可忽略其实现细节,简单当成整数看待。 pthread_mutex_t mutex; 变量mutex只有两种取值1、0。 pthread_mutex_init函数 初始化一个互斥(互斥量) ---> 初值可看作1 int pthread_mutex_init(pthread_mutex_t *restrict mutex, const pthread_mutexattr_t *restrict attr); 参1:传出参数,调用时应传 &mutex restrict关键字:只用于限制指针,告诉编译器,所有修改该指针指向内存中内容的操作,只能通过本指针完成。不能通过除本指针以外的其他变量或指针修改 参2:互斥量属性。是一个传入参数,通常传NULL,选用默认属性(线程间共享)。 参APUE.12.4同步属性 1. 静态初始化:如果互斥 mutex 是静态分配的(定义在全局,或加了static关键字修饰),可以直接使用宏进行初始化。e.g. pthead_mutex_t muetx = PTHREAD_MUTEX_INITIALIZER; 2. 动态初始化:局部变量应采用动态初始化。e.g. pthread_mutex_init(&mutex, NULL) pthread_mutex_destroy函数 销毁一个互斥 int pthread_mutex_destroy(pthread_mutex_t *mutex); pthread_mutex_lock函数 加。可理解为将mutex--(或-1) int pthread_mutex_lock(pthread_mutex_t *mutex); pthread_mutex_unlock函数 解。可理解为将mutex ++(或+1) int pthread_mutex_unlock(pthread_mutex_t *mutex); pthread_mutex_trylock函数 尝试加 int pthread_mutex_trylock(pthread_mutex_t *mutex); 加与解 lock与unlock: lock尝试加,如果加不成功,线程阻塞,阻塞到持有该互斥量的其他线程为止。 unlock主动解函数,同时将阻塞在该上的所有线程全部唤醒,至于哪个线程先被唤醒,取决于优先级、调度。默认:先阻塞、先唤醒。 例如:T1 T2 T3 T4 使用一把mutex。T1加成功,其他线程均阻塞,直至T1解。T1解后,T2 T3 T4均被唤醒,并自动再次尝试加。 可假想mutex init成功初值为1。 lock 功能是将mutex--。 unlock将mutex++ lock与trylock: lock加失败会阻塞,等待释放。 trylock加失败直接返回错误号(如:EBUSY),不阻塞。 加步骤测试: 看如下程序:该程序是非常典型的,由于共享、竞争而没有加任何同步机制,导致产生于时间有关的错误,造成数据混乱: #include #include #include void *tfn(void *arg) { srand(time(NULL)); while (1) { printf("hello "); sleep(rand() % 3); /*模拟长时间操作共享资源,导致cpu易主,产生与时间有关的错误*/ printf("world\n"); sleep(rand() % 3); } return NULL; } int main(void) { pthread_t tid; srand(time(NULL)); pthread_create(&tid, NULL, tfn, NULL); while (1) { printf("HELLO "); sleep(rand() % 3); printf("WORLD\n"); sleep(rand() % 3); } pthread_join(tid, NULL); return 0; } 【mutex.c】 【练习】:修改该程序,使用mutex互斥进行同步。 1. 定义全局互斥量,初始化init(&m, NULL)互斥量,添加对应的destry 2. 两个线程while中,两次printf前后,分别加lock和unlock 3. 将unlock挪至第二个sleep后,发现交替现象很难出现。 线程在操作完共享资源后本应该立即解,但修改后,线程抱着睡眠。睡醒解后又立即加,这两个库函数本身不会阻塞。 所以在这两行代码之间失去cpu的概率很小。因此,另外一个线程很难得到加的机会。 4. main 中加flag = 5 将flg在while中-- 这时,主线程输出5次后试图销毁,但子线程未将释放,无法完成。 5. main 中加pthread_cancel()将子线程取消。 【pthrd_mutex.c】 结论: 在访问共享资源前加,访问结束后立即解的“粒度”应越小越好。 死 1. 线程试图对同一个互斥量A加两次。 2. 线程1拥有A,请求获得B线程2拥有B,请求获得A 【作业】:编写程序,实现上述两种死现象。 读写锁 与互斥量类似,但读写锁允许更高的并行性。其特性为:写独占,读共享。 读写锁状态: 一把读写锁具备三种状态: 1. 读模式下加状态 (读) 2. 写模式下加状态 (写) 3. 不加状态 读写锁特性: 1. 读写锁是“写模式加”时, 解前,所有对该线程都会被阻塞。 2. 读写锁是“读模式加”时, 如果线程以读模式对其加会成功;如果线程以写模式加会阻塞。 3. 读写锁是“读模式加”时, 既有试图以写模式加线程,也有试图以读模式加线程。那么读写锁会阻塞随后的读模式请求。优先满足写模式。读、写并行阻塞,写优先级高 读写锁也叫共享-独占。当读写锁以读模式住时,它是以共享模式住的;当它以写模式住时,它是以独占模式住的。写独占、读共享。 读写锁非常适合于对数据结构读的次数远大于写的情况。 主要应用函数: pthread_rwlock_init函数 pthread_rwlock_destroy函数 pthread_rwlock_rdlock函数 pthread_rwlock_wrlock函数 pthread_rwlock_tryrdlock函数 pthread_rwlock_trywrlock函数 pthread_rwlock_unlock函数 以上7 个函数的返回值都是:成功返回0, 失败直接返回错误号。 pthread_rwlock_t类型 用于定义一个读写锁变量。 pthread_rwlock_t rwlock; pthread_rwlock_init函数 初始化一把读写锁 int pthread_rwlock_init(pthread_rwlock_t *restrict rwlock, const pthread_rwlockattr_t *restrict attr); 参2:attr表读写锁属性,通常使用默认属性,传NULL即可。 pthread_rwlock_destroy函数 销毁一把读写锁 int pthread_rwlock_destroy(pthread_rwlock_t *rwlock); pthread_rwlock_rdlock函数 以读方式请求读写锁。(常简称为:请求读) int pthread_rwlock_rdlock(pthread_rwlock_t *rwlock); pthread_rwlock_wrlock函数 以写方式请求读写锁。(常简称为:请求写) int pthread_rwlock_wrlock(pthread_rwlock_t *rwlock); pthread_rwlock_unlock函数 解 int pthread_rwlock_unlock(pthread_rwlock_t *rwlock); pthread_rwlock_tryrdlock函数 非阻塞以读方式请求读写锁(非阻塞请求读) int pthread_

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值