BDB mutexes are used in two ways:
- As a latch, protect resources (memory data structures, file operations);
- Wait-notifiy. Sets the SELF_BLOCK flag bit. Used in logical lock, group commit when waiting.
Similar to the implementation of MUX_WIN32.C and MUT_TAS.C,
- Spin, through the OS mechanism to go to atomic TAS a lock flag bit; The success exits.
- Spin is unsuccessful, wait-retry. Win32 via WaitForSingleObject, TAS through the OS thread sleep primitive (Win32 unlock, call Plusevent)
In the MUT_PTHREAD.C, do not go to spin
- Pthread_mutex_lock;
- such as Self_block, through pthread_cond_wait do wait. (Call Pthread_cond_signal when unlock)
The DB mutex should provide memory barrier semantics, called Membar_enter () in Tas. x86 does not consider chaos, Pthread Lock provides membar semantics. Pthread will set up pthread_process_shared to provide multi-process support.
Why do we only consider self_block in pthread?
Self_block semantics : Once MTX is initialized, lock once. Once again the lock is locked.
- Win32/tas: Through the TAS sign bit. Since the MTX marker has been set, the lock will spin-wait-retry repeatedly;
- Pthread: The self block cannot be satisfied with Pthread_mutex_lock only. If the same thread two times lock the same MTX, according to the parameters, may deadlock, return error, success, undefined; One thread goes to unlock another thread lock's MTX, also error or undefined.
Http://pubs.opengroup.org/onlinepubs/7908799/xsh/pthread_mutex_lock.html
and the documentation mentions: Mutexes is expected to being locked only for a few instructions.
So you must use conditional variable:
Http://pubs.opengroup.org/onlinepubs/009695399/functions/pthread_cond_timedwait.html
Basically, condition works and Java's wait-notify completely (completely?) Consistent:
- Condition wait before the front-line must have been to get the mutex lock, otherwise undefined;
- Condition wait releases the current mutex lock and the current thread is block.
- Wait is notify, broadcast wakes up (Java notify, notify all?)
- The thread is woken up and needs to get the MTX lock before returning from wait, the same process as pthread_mutex_lock. Didn't get to be block.
- Wait must be placed in while (predict).
MTX: locked unlockedT1: Lock and block. Get MTX lock T2: unlock mtx Wake T1
Finally, MTX is locked in the state.
Study on the self Block mechanism of Berkeley DB