Введение
Механизм синхронизации для обеспечения ограничений на доступ к ресурсу. В информатике замок или мьютекс (от взаимного исключения) — это примитив синхронизации, предотвращающий одновременное изменение или доступ к состоянию несколькими потоками выполнения. Замки обеспечивают соблюдение политик управления конкурентным доступом на основе взаимного исключения, и благодаря разнообразию возможных методов существуют различные уникальные реализации для разных приложений.
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.
Замок базы данных
Блокировки базы данных могут использоваться для обеспечения синхронизации транзакций. То есть, при конкурентной обработке транзакций (перемежающемся выполнении транзакций) использование двухфазных блокировок гарантирует, что параллельное выполнение транзакции эквивалентно некоторой последовательной последовательности транзакций. Однако, взаимные блокировки (дедлоки) являются нежелательным побочным эффектом блокировок в базах данных. Предотвращение взаимных блокировок достигается предварительным определением порядка блокировки между транзакциями, либо их обнаружением с помощью графов ожидания. Альтернативой блокировкам для синхронизации базы данных, позволяющей избежать взаимных блокировок, является использование глобальных меток времени с полным порядком. Существуют механизмы для управления действиями нескольких одновременных пользователей в базе данных, целью которых является предотвращение потери обновлений и "грязного" чтения. Существуют два типа блокировок: пессимистическая и оптимистическая:
Pessimistic locking: a user who reads a record with the intention of updating it places an exclusive lock on the record to prevent other users from manipulating it. This means no one else can manipulate that record until the user releases the lock. The downside is that users can be locked out for a very long time, thereby slowing the overall system response and causing frustration. Where to use pessimistic locking: this is mainly used in environments where data contention (the degree of users request to the database system at any one time) is heavy; where the cost of protecting data through locks is less than the cost of rolling back transactions, if concurrency conflicts occur. Pessimistic concurrency is best implemented when lock times will be short, as in programmatic processing of records. Pessimistic concurrency requires a persistent connection to the database and is not a scalable option when users are interacting with data, because records might be locked for relatively large periods of time. It is not appropriate for use in Web application development. Optimistic locking: this allows multiple concurrent users access to the database whilst the system keeps a copy of the initial read made by each user. When a user wants to update a record, the application determines whether another user has changed the record since it was last read. The application does this by comparing the initial read held in memory to the database record to verify any changes made to the record. Any discrepancies between the initial read and the database record violates concurrency rules and hence causes the system to disregard any update request. An error message is generated and the user is asked to start the update process again. It improves database performance by reducing the amount of locking required, thereby reducing the load on the database server. It works efficiently with tables that require limited updates since no users are locked out. However, some updates may fail. The downside is constant update failures due to high volumes of update requests from multiple concurrent users it can be frustrating for users. Where to use optimistic locking: this is appropriate in environments where there is low contention for data, or where read only access to data is required. Optimistic concurrency is used extensively in NET to address the needs of mobile and disconnected applications, where locking data rows for prolonged periods of time would be infeasible. Also, maintaining record locks requires a persistent connection to the database server, which is not possible in disconnected applications.
Пессимистическая блокировка: пользователь, читающий запись с намерением ее обновить, устанавливает на нее эксклюзивную блокировку, чтобы предотвратить манипуляции с ней другими пользователями. Это означает, что никто другой не сможет изменить эту запись, пока пользователь не снимет блокировку. Недостаток заключается в том, что пользователи могут быть заблокированы на длительное время, что замедляет общую скорость отклика системы и вызывает разочарование. Области применения пессимистической блокировки: она в основном используется в средах с высокой степенью конкуренции за данные (когда большое количество пользователей одновременно обращаются к базе данных); когда стоимость защиты данных с помощью блокировок ниже, чем стоимость отката транзакций в случае возникновения конфликтов параллельного доступа. Пессимистическая блокировка наиболее эффективна, когда время блокировки короткое, например, при программной обработке записей. Пессимистическая блокировка требует постоянного соединения с базой данных и не является масштабируемым решением при взаимодействии пользователей с данными, поскольку записи могут быть заблокированы на относительно длительное время. Она не подходит для разработки веб-приложений.
Pessimistic locking: a user who reads a record with the intention of updating it places an exclusive lock on the record to prevent other users from manipulating it. This means no one else can manipulate that record until the user releases the lock. The downside is that users can be locked out for a very long time, thereby slowing the overall system response and causing frustration. Where to use pessimistic locking: this is mainly used in environments where data contention (the degree of users request to the database system at any one time) is heavy; where the cost of protecting data through locks is less than the cost of rolling back transactions, if concurrency conflicts occur. Pessimistic concurrency is best implemented when lock times will be short, as in programmatic processing of records. Pessimistic concurrency requires a persistent connection to the database and is not a scalable option when users are interacting with data, because records might be locked for relatively large periods of time. It is not appropriate for use in Web application development. Optimistic locking: this allows multiple concurrent users access to the database whilst the system keeps a copy of the initial read made by each user. When a user wants to update a record, the application determines whether another user has changed the record since it was last read. The application does this by comparing the initial read held in memory to the database record to verify any changes made to the record. Any discrepancies between the initial read and the database record violates concurrency rules and hence causes the system to disregard any update request. An error message is generated and the user is asked to start the update process again. It improves database performance by reducing the amount of locking required, thereby reducing the load on the database server. It works efficiently with tables that require limited updates since no users are locked out. However, some updates may fail. The downside is constant update failures due to high volumes of update requests from multiple concurrent users it can be frustrating for users. Where to use optimistic locking: this is appropriate in environments where there is low contention for data, or where read only access to data is required. Optimistic concurrency is used extensively in NET to address the needs of mobile and disconnected applications, where locking data rows for prolonged periods of time would be infeasible. Also, maintaining record locks requires a persistent connection to the database server, which is not possible in disconnected applications.
Оптимистическая блокировка: она позволяет нескольким одновременным пользователям получать доступ к базе данных, при этом система сохраняет копию исходных данных, прочитанных каждым пользователем. Когда пользователь хочет обновить запись, приложение определяет, изменил ли другой пользователь запись с момента ее последнего чтения. Это делается путем сравнения исходных данных, хранящихся в памяти, с записью в базе данных для проверки внесенных изменений. Любое расхождение между исходными данными и записью в базе данных нарушает правила параллельного доступа и, следовательно, система отклоняет запрос на обновление. Генерируется сообщение об ошибке, и пользователю предлагается повторить процесс обновления. Это повышает производительность базы данных за счет уменьшения количества необходимых блокировок, что снижает нагрузку на сервер базы данных. Она эффективно работает с таблицами, требующими ограниченного количества обновлений, поскольку пользователи не блокируются. Однако некоторые обновления могут завершаться неудачно. Недостаток заключается в постоянных сбоях обновления из-за большого количества запросов на обновление от нескольких одновременных пользователей, что может вызывать разочарование у пользователей. Области применения оптимистической блокировки: она подходит для сред с низкой конкуренцией за данные или когда требуется доступ к данным только для чтения. Оптимистическая блокировка широко используется в .NET для решения задач мобильных и автономных приложений, где блокировка строк данных на длительное время нецелесообразна. Кроме того, поддержание блокировок записей требует постоянного соединения с сервером базы данных, что невозможно в автономных приложениях.
Pessimistic locking: a user who reads a record with the intention of updating it places an exclusive lock on the record to prevent other users from manipulating it. This means no one else can manipulate that record until the user releases the lock. The downside is that users can be locked out for a very long time, thereby slowing the overall system response and causing frustration. Where to use pessimistic locking: this is mainly used in environments where data contention (the degree of users request to the database system at any one time) is heavy; where the cost of protecting data through locks is less than the cost of rolling back transactions, if concurrency conflicts occur. Pessimistic concurrency is best implemented when lock times will be short, as in programmatic processing of records. Pessimistic concurrency requires a persistent connection to the database and is not a scalable option when users are interacting with data, because records might be locked for relatively large periods of time. It is not appropriate for use in Web application development. Optimistic locking: this allows multiple concurrent users access to the database whilst the system keeps a copy of the initial read made by each user. When a user wants to update a record, the application determines whether another user has changed the record since it was last read. The application does this by comparing the initial read held in memory to the database record to verify any changes made to the record. Any discrepancies between the initial read and the database record violates concurrency rules and hence causes the system to disregard any update request. An error message is generated and the user is asked to start the update process again. It improves database performance by reducing the amount of locking required, thereby reducing the load on the database server. It works efficiently with tables that require limited updates since no users are locked out. However, some updates may fail. The downside is constant update failures due to high volumes of update requests from multiple concurrent users it can be frustrating for users. Where to use optimistic locking: this is appropriate in environments where there is low contention for data, or where read only access to data is required. Optimistic concurrency is used extensively in NET to address the needs of mobile and disconnected applications, where locking data rows for prolonged periods of time would be infeasible. Also, maintaining record locks requires a persistent connection to the database server, which is not possible in disconnected applications.
Мутекс против семафоров
Семафоры (программирование) #Семафоры и мьютексы