C语言 NOTE37

系统编程之互斥锁



在这里插入图片描述



互斥锁是一种线程间同步使用的变量,在执行的时候,如果一个线程已经获取到了互斥锁,那么另一个在获取时会处于等待状态,此时线程阻塞。只有互斥锁被释放以后,拿到互斥锁的线程才会执行。


如何使用互斥锁?

头文件: #include <pthread.h>
1.初始化互斥锁

int pthread_mutex_init(pthread_mutex_t *restrict_mutex,const pthread_mutexattr_t *restrict_attr);
参数 Value
restrict_mutex 互斥锁变量
restrict_attr 互斥锁属性,默认属性设置为NULL

2.销毁互斥锁

int pthread_mutex_destroy(pthread_mutex_t *mutex);
                                                     ------互斥锁变量

3.加锁动作

int pthread_mutex_lock(pthread_mutex_t *mutex);
                                                      -----互斥锁变量

3.解锁动作

 int pthread_mutex_unlock(pthread_mutex_t *mutex);
                                                       -----互斥锁变量


系统编程之读写锁

重要: 读与读之间不互斥,读与写之间互斥,写与写之间互斥

在这里插入图片描述



如何使用读写锁?

头文件: #include <pthread.h>
1.初始化读写锁

int pthread_rwlock_init(pthread_rwlock_t *restrict rwlock,const pthread_rwlockattr_t *restrict attr);
参数 Value
restrict_rwlock 互斥锁变量
restrict_attr 读写锁属性,默认属性设置为NULL

2.销毁读写锁

 int pthread_rwlock_destroy(pthread_rwlock_t *rwlock);
                                                        -------读写锁变量

3.加读锁

int pthread_rwlock_rdlock(pthread_rwlock_t *rwlock);
                                                        -------读写锁变量

4.加写锁

int pthread_rwlock_wrlock(pthread_rwlock_t *rwlock);
                                                        -------读写锁变量

5.释放读写锁

int pthread_rwlock_unlock(pthread_rwlock_t *rwlock);
                                                         -----读写锁变量

出现死锁

当已经获取到锁,并且正在执行的线程被 突然取消,而此时其他正在等待锁资源的线程,会永远都 拿不到锁,一直等待下去,这种情况称为死锁。

解决办法:
(1)在死锁发生之前,注册一个解锁的函数
(2)把线程设置成不可取消

#include <pthread.h>
void pthread_cleanup_push(void (*routine)(void *),--->函数
                                 void *arg);				--->函数传参
            传参时候一般传锁的变量的地址

 void pthread_cleanup_pop(int execute);		
                --->数值为0时,表示将注册的函数删除掉

在执行注册函数pthread_cleanup_push的时候,被注册的函数func并不会被运行,只有在线程被取消的时候,才会运行注册的函数func。



条件变量

条件变量是为了某一些 公用资源 的线程在等待过程中,能够释放出锁资源,防止CPU长时间的浪费。
在这里插入图片描述



如何使用条件变量?

1.初始化条件变量

int pthread_cond_init(pthread_cond_t *restrict cond,
                                    ------条件变量名称
              const pthread_condattr_t *restrict attr);
                                    -----条件变量属性

2.销毁条件变量

 int pthread_cond_destroy(pthread_cond_t *cond);
                                    ------条件变量名称

3.通过条件变量释放锁资源,然后等待条件变量

 int pthread_cond_wait(pthread_cond_t *restrict cond,
                                    ------需要等待的条件变量
              pthread_mutex_t *restrict mutex);
                                    ------被释放的锁资源

4.群发条件变量:告诉所有正在等待线程

 int pthread_cond_broadcast(pthread_cond_t *cond); 
                                    ------被发送的条件变量

5.私发条件变量:只给第一个等待的线程发送消息

int pthread_cond_signal(pthread_cond_t *cond);
                                    ------被发送的条件变量
发布了52 篇原创文章 · 获赞 2 · 访问量 1989

猜你喜欢

转载自blog.csdn.net/weixin_42191545/article/details/104247429