Sample code for demonstrating different behavior in different pthread type
- PTHREAD_MUTEX_NORMAL
- This type of mutex does not detect deadlock
- A thread attempting to relock this mutex without first unlocking it shall deadlock
- A thread attempting to unlock a mutex locked by a different thread results in undefined behavior
- A thread attempting to unlock an unlocked mutex results in undefined behavior
- PTHREAD_MUTEX_ERRORCHECK
- This type of mutex provides error checking
- A thread attempting to relock this mutex without first unlocking it shall return with an error
- A thread attempting to unlock a mutex which another thread has locked shall return with an error
- A thread attempting to unlock an unlocked mutex shall return with an error
- PTHREAD_MUTEX_RECURSIVE
- A thread attempting to relock this mutex without first unlocking it
shall succeed in locking the mutex
- The relocking is allowd only in the same thread
- 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 shall 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 shall return with an error
- A thread attempting to unlock an unlocked mutex shall return with an error
- A thread attempting to relock this mutex without first unlocking it
shall succeed in locking the mutex
- PTHREAD_MUTEX_DEFAULT
- Its default value is set to PTHREAD_MUTEX_NORMAL
- It's allowed to map its value to other types
We have four scenarios:
- Lock a locked mutex in same thread
- Unlock a unlocked mutex
- (Wait to) Lock a locked mutex owned by another thread (normal use case)
- Unlock a locked mutex owned by another thread
Unlocking a mutex owned by current thread is definitely ok, so it's exclusive in our scenarios.
The results of our scenarios in different type is:
1 | 2 | 3 | 4 | |
---|---|---|---|---|
NORMAL | ! | v | v | v |
ERRORCHECK | v | |||
RECURSIVE | v | v | ||
DEFAULT | ! | v | v | v |
!
: It works without any error, but it will be self-deadlockedv
: It works without any error- empty: It can not works, with an error returned
- Sample code for
pthread_kill
andpthread_detach
The pthread_mutex_trylock()
shall be equivalent
to pthread_mutex_lock()
,
except that if the mutex object referenced by mutex is currently locked
(by any thread, including the current thread),
the call shall return immediately.