MySQL ---- Lock knowledge

lock

We know a lot of support in mysql storage engines, under different storage engines can support lock is different, we have to look at by comparing MyISAM and InnoDB.

Table level lock (table-level)

Table-level locking is MySQL storage engine in each maximum granularity of locking mechanism. The greatest feature of the locking mechanism is to implement logic is very simple, minimal negative impact on the system brings. So acquiring the lock and release the lock quickly. Due to a table-level lock will lock the entire table, it can be good to avoid deadlock plaguing us.
Of course, the probability of lock contention resource lock large particles of the biggest is the emergence of the negative impact will be the highest, resulting in greatly reduced and generous.
Table-level locking is mainly MyISAM, MEMORY, CSV and some other non-transactional storage engine.

Row-level locking    

Row-level locking biggest feature is to lock the object is very small particles, is currently locked in major database management software to achieve the minimum granularity. Since the locking granularity is small, so the probability of occurrence locked resource contention is minimal, the application can give the greatest possible number of concurrent processing capability and improve concurrent applications that require high overall system performance.
Even though it can have a greater advantage in the above concurrent processing capability, but row-level locking that brought a number of shortcomings. Since the locking granularity little resources, so every time things get and release locks also need to do more to bring the consumption of naturally greater. In addition, row-level locking is also the most prone to deadlock.
Use row-level locking InnoDB storage engine primarily.

Table-level lock: Small overhead, lock fast; not deadlock; lock large size, the probability of lock conflicts of the highest, lowest degree of concurrency;
row-level locking: large overhead, locking slow; there will be a deadlock; locking granularity the smallest, lowest probability of lock conflicts, but also the highest degree of concurrency;

Optimistic and pessimistic locking

Optimistic locking , by definition, to lock hold an optimistic attitude, which is to be operational, not the last step not locked, "optimistic" locking think will be successful, the last step to update data when performing locking, optimistic locking implementations typically each piece of data plus a version number, the specific process is as follows:

1), adding a version when you create a table field that indicates the version number, as follows:
    img

2), modify the data when the first version of this article check out the data to determine whether the version number and the database is consistent, if this agreement indicates that the data was not modified by other users when the update, if it indicates that this is inconsistent during operation of data modified by other customers, in this case need to throw exception rollback code or the like. Pseudo-code as follows:

update tb set name='yyy' and version=version+1 where id=1 and version=version;

1. SELECT name AS old_name, version AS old_version FROM tb where ...;
2. 根据获取的数据进行业务操作,得到new_dname和new_version
3. UPDATE SET name = new_name, version = new_version WHERE version = old_version
if (updated row > 0) {
    // 乐观锁获取成功,操作完成
} else {
    // 乐观锁获取失败,回滚并重试

}

In fact, it does not matter in the update are not things inside like this: update is single-threaded, and if a thread of a data update operation, will acquire a lock, other threads will be blocked if you want to operate the data on the same until after the successful release lock this thread update.

Pessimistic locking , as its name suggests, pessimistic locking locking the data hold a pessimistic attitude. Thus, the entire data processing, the data is locked. Implement pessimistic locking, often rely lock mechanism provided by the database (the database layer, only lock mechanism provided in order to truly ensure exclusive access to the data, otherwise, to achieve a locking mechanism even in this system, there is no guarantee does not modify the external system data).

  First, we need to set autocommit = 0, which does not allow automatic submission

  用法:select * from tablename where id = 1 for update;

  Application premise: There is no row of the result set data thread using an exclusive or shared lock, otherwise the application will be blocked.

  for update applies only to InnoDB, and must take effect at the transaction block (BEGIN / COMMIT) in. When the transaction operation is performed by "for update" statement, MySQL will query result set each row of data add exclusive lock, other threads update and delete the record of operation will block. Exclusive lock contains the line lock, table lock.

  Suppose a product table Shop, comprising id, trade name, inventory three fields, the table structure is as follows:

  img

  Insert the following data:

  img

  

  Concurrent lead to data consistency problems:

  If there are A, B two users need to purchase goods id = 1, the number of AB are queries merchandise is 1000, modified A purchase quantity of 999, modified B purchase quantity is 999.

  With optimistic locking solution:

Each time acquiring goods, the goods do not lock. Need to compare programs stocks and inventory database updated data are equal in time, if equal to update, otherwise the program retrieve inventory, compare again until the two values ​​are equal before the inventory data updates . Pseudo-code as follows:

//不加锁
select id,name,stock where id=1;
 
//业务处理
 
begin;
 
update shop set stock=stock-1 where id=1 and stock=stock;
 
commit;

Pessimistic locking scheme:

Each time to get goods, the goods plus exclusive lock. That is, get the get locked rows when id = 1 product information in the user A, other users during the block waiting for access to the records. Pessimistic locking writes frequently for the scene. code show as below:

begin;
 
select id,name,stock as old_stock from shop  where id=1 for update;
 
update shop set stock=stock-1 where id=1 and stock=old_stock;
 
commit;

We can see things through a first open begin, are locking the data in the entire process of acquiring shop information and modify data, to ensure data consistency.

Guess you like

Origin www.cnblogs.com/zhufanyu/p/12129449.html