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

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

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);
            }
      }
}

你可能感兴趣的:(对于多线程的锁的异常处理)