对于多线程的锁的异常处理

对于多线程的锁来说,如果某个线程获取了这个锁,但该线程挂掉了,然后锁就不会释放了。对于这种问题,只需要在锁初始化的时候设置锁的属性。

pthread_mutexattr_t mutexattr;
pthread_mutexattr_t mutexattr;
pthread_mutexattr_init(&mutexattr);
pthread_mutexattr_setprotocol(&mutexattr, PTHREAD_PRIO_INHERIT);
pthread_mutexattr_setpshared(&mutexattr,PTHREAD_PROCESS_SHARED);
pthread_mutexattr_setrobust_np(&mutexattr,PTHREAD_MUTEX_STALLED_NP);
pthread_mutex_init(&(g_halog_shm_ptr->ha_log_shm_mutex), &mutexattr);

pthread_mutexattr_setrobust_np

PTHREAD_MUTEX_ROBUST_NP

When the owner of the mutex dies, all subsequent calls to pthread_mutex_lock() are blocked from progress in an unspecified manner.

PTHREAD_MUTEX_STALLED_NP

When the owner of the mutex dies, the mutex is unlocked. The next owner of this mutex acquires it with an error return of EOWNWERDEAD.

pthread_mutexattr_setrobust_np

PTHREAD_PRIO_NONE

When a thread owns a mutex with the PTHREAD_PRIO_NONE protocol attribute, its priority and scheduling shall not be affected by its mutex ownership.
线程的优先级不会因为锁的拥有而改变。

PTHREAD_PRIO_INHERIT

使用PTHREAD_PRIO_INHERIT,持有锁的线程会继承当前争用锁的最高线程优先级,如果没有其它线程争用,那优先级不会变化。

PTHREAD_PRIO_PROTECT

这个和PTHREAD_PRIO_INHERIT 的区别在于不会因为其它的线程而变化,而是根据锁的属性的优先级来确定的,可以通过pthread_mutexattr_setprioceiling 来设置锁的优先级。

void ha_log_lock_shm_mutex(void)
{
  int lock_result = pthread_mutex_lock(&g_halog_shm_ptr->ha_log_shm_mutex);
        /*如果返回EOWNERDEAD则调用pthread_mutex_consistent_np统一锁的状态。然后unlock再lock。如果返回ENOTRECOVERABLE,则pthread_mutex_destroy销毁,然后再重新init锁。*/
    if(lock_result == EOWNERDEAD){
        if(pthread_mutex_consistent_np(&g_halog_shm_ptr->ha_log_shm_mutex) == 0){
            pthread_mutex_unlock(&g_halog_shm_ptr->ha_log_shm_mutex);
            pthread_mutex_lock(&g_halog_shm_ptr->ha_log_shm_mutex);
        }else{
            pthread_mutex_destroy(&g_halog_shm_ptr->ha_log_shm_mutex);
            ha_log_init_shm_mutex();
            pthread_mutex_lock(&g_halog_shm_ptr->ha_log_shm_mutex);
        }
      }else{
            if(lock_result == ENOTRECOVERABLE){
                pthread_mutex_destroy(&g_halog_shm_ptr->ha_log_shm_mutex);
                ha_log_init_shm_mutex();
                pthread_mutex_lock(&g_halog_shm_ptr->ha_log_shm_mutex);
            }
      }
}
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 转载:谈 iOS 的锁 又到了春天挪坑的季节,想起多次被问及到锁的概念,决定好好总结一番。 翻看目前关于 iOS ...
    小鲲鹏阅读 583评论 0 0
  • 转发:LockForiOS 又到了春天挪坑的季节,想起多次被问及到锁的概念,决定好好总结一番。 翻看目前关于 iO...
    Cooci_和谐学习_不急不躁阅读 2,323评论 1 22
  • Q:为什么出现多线程? A:为了实现同时干多件事的需求(并发),同时进行着下载和页面UI刷新。对于处理器,为每个线...
    幸福相依阅读 1,697评论 0 2
  • 在编程中,引入了对象互斥锁的概念,来保证共享数据操作的完整性。每个对象都对应于一个可称为" 互斥锁" 的标记,这个...
    wtqhy14615阅读 1,053评论 0 1
  • 多线程系列文章源码头文件内容: #include #include #include 作为程序员,就是要减少重复劳...
    batbattle阅读 1,053评论 0 1

友情链接更多精彩内容