线程同步---互斥锁和读写锁

同步概念
  • 所谓同步,即同时起步,协调一致。不同的对象,对“同步”的理解方式略有不同。如,设备同步,是指在两个设备之间规定一个共同的时间参考;数据库同步,是指让两个或多个数据库内容保持一致,或者按需要部分保持一致;文件同步,是指让两个或多个文件夹里的文件保持一致。等等
  • 但是在编程中、通信中所说的同步与生活中大家印象中的同步概念略有差异。“同”字应是指协同、协助、互相配合。主旨在协同步调,按预定的先后次序运行。
线程同步
  • 同步即协同步调,按预定的先后次序运行。
  • 线程同步,指一个线程发出某一功能调用时,在没有得到结果之前,该调用不返回。同时其它线程为保证数据一致性,不能调用该功能。
  • 举个例子: 内存中100字节,线程T1欲填入全1, 线程T2欲填入全0。但如果T1执行了50个字节后失去了cpu,T2抢到了cpu执行填入全0,会将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. 参1:传出参数,调用时应传 &mutex	
	2. estrict关键字:只用于限制指针,告诉编译器,所有修改该指针指向内存中内容的操作,只能通过本指针完成。不能通过除本指针以外的其他变量或指针修改
	3. 参2:互斥量属性。是一个传入参数,通常传NULL,选用默认属性(线程间共享)。 
  1. 静态初始化:如果互斥锁 mutex 是静态分配的(定义在全局,或加了static关键字修饰),可以直接使用宏进行初始化。
    例如:pthead_mutex_t muetx = PTHREAD_MUTEX_INITIALIZER
  2. 动态初始化:局部变量应采用动态初始化。
    例如: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和trylock)

  • lock尝试加锁,如果加锁不成功,线程阻塞,阻塞到持有该互斥量的其他线程解锁为止。
  • unlock 主动解锁函数,同时将阻塞在该锁上的所有线程全部唤醒,至于哪个线程先被唤醒,取决于优先级、调度。默认:先阻塞的线程、先被唤醒。
    例如:T1 T2 T3 T4 使用一把mutex锁。T1加锁成功,其他线程均阻塞,直至T1解锁。T1解锁后,T2 T3 T4均被唤醒,并自动再次尝试加锁。
  • 可假想mutex锁 init 成功初值为1。lock 功能是将mutex- -。 unlock将mutex++
  • lock与trylock:
    1. lock加锁失败会阻塞,等待锁释放。
    2. trylock加锁失败直接返回错误号(如:EBUSY),不阻塞。
代码:未加锁的程序
  1 #include <stdio.h>
  2 #include <pthread.h>
  3 #include <unistd.h>
  4 
  5 void *tfn(void *arg)
  6 {
  7     srand(time(NULL));
  8     while (1) {
  9 
 10         printf("hello ");
 11         sleep(rand() % 3);  /*模拟长时间操作共享资源,导致cpu易主,产生与时间有关的错误*/
 12         printf("world\n");
 13         sleep(rand() % 3);
 14     }
 15     return NULL;
 16 }
 17 int main(void)
 18 {
 19     pthread_t tid;
 20     srand(time(NULL));
 21     pthread_create(&tid, NULL, tfn, NULL);
 22     while (1) {
 23         printf("HELLO ");
 24         sleep(rand() % 3);
 25         printf("WORLD\n");
 26         sleep(rand() % 3);
 27     }
 28     pthread_join(tid, NULL);
 29     return 0;
 30 }

在这里插入图片描述

  • 我们会发现在上面的程序中,由于我们没有加锁,当一个线程执行的时候,可能会失去cpu,导致自身的工作挂起,而去执行另外的线程。会出现如上输出的乱序。
  • 但是如果加锁,就不会出现这种情况。
  1 #include <stdio.h>
  2 #include <pthread.h>
  3 #include <unistd.h>
  4 
  5 pthread_mutex_t mutex;
  6 
  7 void *tfn(void *arg)
  8 {
  9     srand(time(NULL));
 10     while (1) {
 11         pthread_mutex_lock(&mutex);
 12         printf("hello ");
 13         sleep(rand() % 3);  /*模拟长时间操作共享资源,导致cpu易主,产生与时间有关的错误*/
 14         printf("world\n");
 15         pthread_mutex_unlock(&mutex);
 16         sleep(rand() % 3);
 17     }
 18     return NULL;
 19 }
 20 int main(void)
 21 {
 22     pthread_t tid;
 23     srand(time(NULL));
 24     pthread_mutex_init(&mutex,NULL);
 25     pthread_create(&tid, NULL, tfn, NULL);
 26     while (1) {
 27         pthread_mutex_lock(&mutex);
 28         printf("HELLO ");
 29         sleep(rand() % 3);
 30         printf("WORLD\n");
 31         pthread_mutex_unlock(&mutex);
 32         sleep(rand() % 3);
 33     }
 34     pthread_join(tid, NULL);
 35     pthread_mutex_destroy(&mutex);
 36     return 0;
 37 }

在这里插入图片描述

  • 在访问共享资源前加锁,访问结束后立即解锁。锁的“粒度”应越小越好。
死锁
  1. 线程试图对同一个互斥量A加锁两次。
  2. 线程1拥有A锁,请求获得B锁;线程2拥有B锁,请求获得A锁
  • 程序,实现上述两种死锁现象。
  • 第一种情况:
  1 #include<stdio.h>
  2 #include<pthread.h>
  3 
  4 pthread_mutex_t mutex;
  5 
  6 int main()
  7 {
  8     int a = 100;
  9 
 10     pthread_mutex_init(&mutex,NULL);
 11     pthread_mutex_lock(&mutex);
 12     pthread_mutex_lock(&mutex);
 13     a = 200;
 14     pthread_mutex_unlock(&mutex);
 15     pthread_mutex_destroy(&mutex);
 16     return 0;
 17 }

  • 程序会一直停在那里等待。阻塞等待。
  • 第二种情况
    1 #include<string.h>                                                                                                                                               
    2 #include<stdlib.h>
    3 #include<pthread.h>
    4 #include<unistd.h>
    5 #include<stdio.h>
    6 
    7 pthread_mutex_t mutex1,mutex2;
    8 int a = 100, b = 100;
    9 
   10 void* sfn(void* arg)
   11 {
   12     int count = *(int*)arg;
   13     if(count == 1)
   14     {
   15         pthread_mutex_lock(&mutex1);
   16         a = 200;
   17         printf("aaaaaaaaaaaa1\n");
   18         sleep(5);    //为了让另外一个线程拿到cpu
   19         printf("aaaaaaaaaaa2\n");
   20         pthread_mutex_lock(&mutex2);
   21         b = 200;
   22         pthread_mutex_unlock(&mutex2);
   23         pthread_mutex_unlock(&mutex1);
   24 
   25         printf("thread finish %d\n",count);
   26         pthread_exit(NULL);
   27     }
   28     if(count == 2)
   29     {
   30         printf("bbbbbbbbbbbb\n");
   31         pthread_mutex_lock(&mutex2);
   32         a = 300;
   33         pthread_mutex_lock(&mutex1);
   34         b = 300;
   35         pthread_mutex_unlock(&mutex1);
   36         pthread_mutex_unlock(&mutex2);
   37 
   38         printf("thread finish %d\n",count);
   39         pthread_exit(NULL);
   40     }
   41     return NULL;
   42 }
   43 
   44 int main()
   45 {
   46     pthread_t tid1,tid2;
   47     int ret;
   48 
   49     pthread_mutex_init(&mutex1,NULL);
   50     pthread_mutex_init(&mutex2,NULL);
   51 
   52     int argument1 = 1;
   53     int* p1 = &argument1;                                                                                                                                        
   54     ret = pthread_create(&tid1,NULL,sfn,(void*)p1);
   55     if(ret != 0)
   56     {
   57         fprintf(stderr,"pthread create error : %lu\n",strerror(ret));
   58         exit(0);
   59     }
   60     int argument2 = 2;
   61     int *p2 = &argument2;
   62     ret = pthread_create(&tid2,NULL,sfn,(void*)p2);
   63     if(ret != 0)
   64     {
   65         fprintf(stderr,"pthread create error : %lu\n",strerror(ret));
   66         exit(1);
   67     }
   68 
   69     sleep(100);  // 为了不让主线程在子线程之前退出 
   70     pthread_mutex_destroy(&mutex1);
   71     pthread_mutex_destroy(&mutex2);
   72 
   73     pthread_join(tid1,NULL);
   74     pthread_join(tid2,NULL);
   75 
   76     printf("last val a = %d, b = %d\n",a,b);
   77     return 0;
   78 }
  • 这就像我拿了一个钻石,你拿了黄金,我说,你先把黄金给我,我在把钻石给你;你说你先把钻石给我,我在把黄金给你。然后我们两个就在这里耗着,一直在耗着。。。
读写锁
  • 与互斥量类似,但读写锁允许更高的并行性。其特性为:写独占,读共享
  • 读写锁状态:
  • 一把读写锁具备三种状态:
    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);
	参1:读写锁 rwlock,加上 restrict 关键字表示这块内存空间只能由rwlock这个指针访问。 
	参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_rwlock_tryrdlock(pthread_rwlock_t *rwlock);
  • pthread_rwlock_trywrlock函数,非阻塞以写方式请求读写锁(非阻塞请求写锁)
    int pthread_rwlock_trywrlock(pthread_rwlock_t *rwlock);
读写锁代码
  1 #include <stdio.h>
  2 #include <unistd.h>
  3 #include <pthread.h>
  4 
  5 int counter;
  6 pthread_rwlock_t rwlock;
  7 
  8 /* 3个线程不定时写同一全局资源,5个线程不定时读同一全局资源 */
  9 void *th_write(void *arg)
 10 {
 11     int t, i = (int)arg;
 12     while (1) {
 13         pthread_rwlock_wrlock(&rwlock);
 14         t = counter;
 15         usleep(1000);
 16         printf("=======write %d: %lu: counter=%d ++counter=%d\n", i, pthread_self(), t, ++counter);
 17         pthread_rwlock_unlock(&rwlock);
 18         usleep(10000);
 19     }
 20     return NULL;
 21 }
 22 void *th_read(void *arg)
 23 {
 24     int i = (int)arg;
 25 
 26     while (1) {
 27         pthread_rwlock_rdlock(&rwlock);
 28         printf("----------------------------read %d: %lu: %d\n", i, pthread_self(), counter);
 29         pthread_rwlock_unlock(&rwlock);
 30         usleep(2000);
 31     }
 32     return NULL;
 33 }
 34 int main(void)
 35 {
 36     int i;
 37     pthread_t tid[8];
 38     pthread_rwlock_init(&rwlock, NULL);
 39 
 40     for (i = 0; i < 3; i++)
 41         pthread_create(&tid[i], NULL, th_write, (void *)i);
 42     for (i = 0; i < 5; i++)
 43         pthread_create(&tid[i+3], NULL, th_read, (void *)i);
 44     for (i = 0; i < 8; i++)
 45         pthread_join(tid[i], NULL);
 46 
 47     pthread_rwlock_destroy(&rwlock);
 48     return 0;
 49 }

在这里插入图片描述

  • 我们可以看到一个线程对资源加了读锁时,别的线程还可以对该资源加读锁。但是如果一个线程对资源加了写锁时,别的线程就不能再给此资源进行加写锁了。所以我们可以看到上图中写锁基本上是一个出现,而读锁可以一大堆同时出现。
  • 1
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 5
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值