All kinds of locks (mutex, spin locks, read-write locks, optimistic locking, pessimistic locking, deadlocks)

Mutex

When one thread to access shared resources (critical resource) code (critical area) before accessing the thread will be locked. If you want other threads access to critical resources before did not release the lock after lock, these threads will be blocked sleep until the release, there are one or more thread blocks if unlocked, then these will become locked threads ready state, then first become ready thread will acquire the right to use the resource, and locked again, blocking other threads continue to wait.

Read-Write Lock

Also known as shared mutex, shared read mode, write mode are mutually exclusive. A bit like a separate read and write mode database load balancing. It has three modes: read lock state, write lock state and an unlocked state. In simple terms there is only one thread can occupy write mode read-write locks, but there may be occupied by multiple threads read mode to read and write locks.
When the write locked mode, any thread locking its operation will be blocked until unlocked.
When locked in read mode, any thread can be locked read operation, but all attempts to write thread-locking operation will be blocked. Until all the threads read unlock. But when too many threads to read, write thread has been blocked is obviously wrong, it is a thread wants to write its lock, the lock will block read, write let locking thread lock

Spinlocks

Mutex lock and spin like, the only difference is that when the spin lock lock access to resources, would have been circulating to see if the lock is released. So much higher than the mutex lock efficiency, but will only take up CPU. So spin lock is suitable for multi-core CPU. But there is a problem is when the spin lock recursive call can cause deadlock. Therefore, careful use of spin locks.

Optimistic locking

In fact, this is an idea, when the threads get data that another thread does not modify the data is not locked, but when will the update data to judge whether the following additional threads to modify the data. Judged by version, if the data is modified refused to update, I was called optimistic because the lock is not locked.

Pessimistic locking

When a thread Where data, always think the other thread to modify data, so every time it will take the data lock, other threads get when data will be blocked.
Both locks are generally used for the database, a database when the read operation is far greater than the number of write operations, the use of optimistic locking will increase the throughput of the database.

Guess you like

Origin www.cnblogs.com/mjtabu/p/11940028.html