/* Mutex types. */
enum
{
PTHREAD_MUTEX_TIMED_NP,
PTHREAD_MUTEX_RECURSIVE_NP,
PTHREAD_MUTEX_ERRORCHECK_NP,
PTHREAD_MUTEX_ADAPTIVE_NP
#if defined __USE_UNIX98 || defined __USE_XOPEN2K8
,
PTHREAD_MUTEX_NORMAL = PTHREAD_MUTEX_TIMED_NP,
PTHREAD_MUTEX_RECURSIVE = PTHREAD_MUTEX_RECURSIVE_NP,
PTHREAD_MUTEX_ERRORCHECK = PTHREAD_MUTEX_ERRORCHECK_NP,
PTHREAD_MUTEX_DEFAULT = PTHREAD_MUTEX_NORMAL
#endif
#ifdef __USE_GNU
/* For compatibility. */
, PTHREAD_MUTEX_FAST_NP = PTHREAD_MUTEX_TIMED_NP
#endif
};
attr
DEFAULT
与 NORMAL
属性有太多的未定义行为,应该尽可能的避免使用。NORMAL
会导致死锁,并不会返回错误代码,因而程序会卡住。互斥锁默认属性为 NORMAL
ERRORCHECK
重复加锁,重复解锁都会返回错误代码,不会导致死锁
RECURSIVE
允许同一线程进行N次加锁,但必须进行N次解锁才能释放这把锁
pthread_mutexattr_settype(&mutex_attr, PTHREAD_MUTEX_ERRORCHECK);
Ref
- POS04-C. Avoid using PTHREAD_MUTEX_NORMAL type mutex locks
- pthread_mutex_lock
- POSIX 设置锁的属性
- pthread_mutexattr_settype(3) - Linux man page