Lock (computer science)

In computer science, a lock or mutex (from mutual exclusion) is a synchronization primitive that prevents state from being modified or accessed by multiple threads of execution at once.

Locks enforce mutual exclusion concurrency control policies, and with a variety of possible methods there exist multiple unique implementations for different applications.

This is efficient if threads are blocked for a short time, because it avoids the overhead of operating system process re-scheduling.

In general, choosing a coarse granularity (a small number of locks, each protecting a large segment of data) results in less lock overhead when a single process is accessing the protected data, but worse performance when multiple processes are running concurrently.

An alternate to locking for database synchronicity while avoiding deadlocks involves the use of totally ordered global timestamps.

There are mechanisms employed to manage the actions of multiple concurrent users on a database—the purpose is to prevent lost updates and dirty reads.

The following is an example with the common, major lock types: Comment: In some publications, the table entries are simply marked "compatible" or "incompatible", or respectively "yes" or "no".

[5] Lock-based resource protection and thread/process synchronization have many disadvantages: Some concurrency control strategies avoid some or all of these problems.

Alternatives to locking include non-blocking synchronization methods, like lock-free programming techniques and transactional memory.

However, such alternative methods often require that the actual lock mechanisms be implemented at a more fundamental level of the operating software.

[citation needed] One of lock-based programming's biggest problems is that "locks don't compose": it is hard to combine small, correct lock-based modules into equally correct larger programs without modifying the modules or at least knowing about their internals.

A transfer routine that is correct for sequential programs would be In a concurrent program, this algorithm is incorrect because when one thread is halfway through transfer, another might observe a state where amount has been withdrawn from the first account, but not yet deposited into the other account: money has gone missing from the system.

Programming languages vary in their support for synchronization: A mutex is a locking mechanism that sometimes uses the same basic implementation as the binary semaphore.