Linux互斥锁与死锁风险概述
在Linux环境下,互斥锁是实现多线程间资源同步与保护的常用工具。然而,当程序逻辑的时序关系变得复杂时,开发者很容易陷入死锁的困境。
为了解决由同一线程重复获取未释放锁所引发的死锁问题,系统提供了设置锁属性的机制。
具体实现可通过调用 pthread_mutexattr_settype 函数来完成,该函数接收指向 mutexattr_t 结构体的指针以及指定的类型参数。
通常支持以下四种主要的锁属性类型:
PTHREAD_MUTEX_NORMAL
This type of mutex does not detect deadlock. A thread attempting to relock this mutex without first unlocking it will deadlock. Attempting to unlock a mutex locked by a different thread results in undefined behaviour. Attempting to unlock an unlocked mutex results in undefined behaviour.
PTHREAD_MUTEX_ERRORCHECK
This type of mutex provides error checking. A thread attempting to relock this mutex without first unlocking it will return with an error. A thread attempting to unlock a mutex which another thread has locked will return with an error. A thread attempting to unlock an unlocked mutex will return with an error.
PTHREAD_MUTEX_RECURSIVE
A thread attempting to relock this mutex without first unlocking it will succeed in locking the mutex. The relocking deadlock which can occur with mutexes of type PTHREAD_MUTEX_NORMAL cannot occur with this type of mutex. Multiple locks of this mutex require the same number of unlocks to release the mutex before another thread can acquire the mutex. A thread attempting to unlock a mutex which another thread has locked will return with an error. A thread attempting to unlock an unlocked mutex will return with an error.
PTHREAD_MUTEX_DEFAULT
Attempting to recursively lock a mutex of this type results in undefined behaviour. Attempting to unlock a mutex of this type which was not locked by the calling thread results in undefined behaviour. Attempting to unlock a mutex of this type which is not locked results in undefined behaviour. An implementation is allowed to map this mutex to one of the other mutex types.
需要明确的是,上述关于重复加锁的限制主要针对同一线程。对于不同线程而言,无论设置何种属性,一旦锁已被锁定,后续尝试加锁的操作均会进入互斥阻塞状态。
若使用 PTHREAD_MUTEX_RECURSIVE 属性,当同一线程在未解锁的情况下再次尝试锁定该锁时,操作将返回成功而非阻塞,从而允许递归访问。
以上即为Linux系统中关于多线程互斥锁属性设置的完整方法介绍,希望能帮助读者更好地掌握这一技术细节。