blog » MongoDB » mongodb的锁机制
What type of locking does MongoDB use?
MongoDB uses a readers-writer  lock that allows concurrent reads access to a database but gives exclusive access to a single write operation.
When a read lock exists, many read operations may use this lock. However, when a write lock exists, a single write operation holds the lock exclusively, and no other read or write operations may share the lock.
Locks are “writer greedy,” which means writes have preference over reads. When both a read and write are waiting for a lock, MongoDB grants the lock to the write.
How granular are locks in MongoDB?
Changed in version 2.2.
Beginning with version 2.2, MongoDB implements locks on a per-database basis for most read and write operations. Some global operations, typically short lived operations involving multiple databases, still require a global “instance” wide lock. Before 2.2, there is only one “global” lock per mongod instance.
For example, if you have six databases and one takes a write lock, the other five are still available for read and write.
How do I see the status of locks on my mongod instances?
For reporting on lock utilization information on locks, use any of the following methods:
the MongoDB Monitoring Service (MMS)
Specifically, the locks document in the output of serverStatus, or the locks field in the current operation reporting provides insight into the type of locks and amount of lock contention in your mongod instance.
To terminate an operation, use db.killOp().
Does a read or write operation ever yield the lock?
New in version 2.0.
A read and write operations will yield their locks if the mongod receives a page fault or fetches data that is unlikely to be in memory. Yielding allows other operations that only need to access documents that are already in memory to complete while mongod loads documents into memory.
Additionally, write operations that affect multiple documents (i.e. update() with the multi parameter,) will yield periodically to allow read operations during these log write operations. Similarly, long running read locks will yield periodically to ensure that write operations have the opportunity to complete.
Changed in version 2.2: The use of yielding expanded greatly in MongoDB 2.2. Including the “yield for page fault.” MongoDB tracks the contents of memory and predicts whether data is available before performing a read. If MongoDB predicts that the data is not in memory a read operation yields its lock while MongoDB loads the data to memory. Once data is available in memory, the read will reacquire the lock to completes the operation.
This post has already been read 1839 times!