Detecting locked tables (locked by LOCK TABLE)

前端 未结 8 1610
野趣味
野趣味 2020-11-29 18:46

Is there a way to detect locked tables in MySQL? I mean tables locked by the LOCK TABLE table WRITE/READ command.

(Note that readers interested in

相关标签:
8条回答
  • 2020-11-29 19:22

    You can use SHOW OPEN TABLES to show each table's lock status. More details on the command's doc page are here.

    0 讨论(0)
  • 2020-11-29 19:23

    SHOW OPEN TABLES to show each table status and its lock.

    For named locks look Show all current locks from get_lock

    0 讨论(0)
  • 2020-11-29 19:31

    Use SHOW OPEN TABLES: http://dev.mysql.com/doc/refman/5.1/en/show-open-tables.html

    You can do something like this

    SHOW OPEN TABLES WHERE `Table` LIKE '%[TABLE_NAME]%' AND `Database` LIKE '[DBNAME]' AND In_use > 0;
    

    to check any locked tables in a database.

    0 讨论(0)
  • 2020-11-29 19:32

    The following answer was written by Eric Leschinki in 2014/15 at https://stackoverflow.com/a/26743484/1709587 (now deleted):

    Mini walkthrough on how to detect locked tables:

    This may prevent the database from enforcing atomicity in the affected tables and rows. The locks were designed to make sure things stay consistent and this procedure will prevent that process from taking place as designed.

    Create your table, insert some rows

    create table penguins(spam int, ham int);
    insert into penguins(spam, ham) values (3, 4);
    

    show open tables:

    show open tables like "penguins"
    

    prints:

    your_database penguins    0   0
    

    Penguins isn't locked, lets lock it:

    LOCK TABLES penguins READ;
    

    Check if it's locked:

    show open tables like "penguins"
    

    Prints:

    your_database, penguins 1, 0
    

    Aha! It is locked! Lets unlock it:

    unlock tables
    

    Now it is unlocked:

    show open tables like "penguins"
    

    Prints:

    your_database penguins    0   0
    

    show all current locks

    show open tables where in_use <> 0
    

    It would be much more helpful if the MySQL developers put this information in a regular table (so I can do a select my_items from my_table where my_clauses), rather than this stripped down 'show table' syntax from system variables.

    0 讨论(0)
  • 2020-11-29 19:37

    The simplest way is :

    SHOW OPEN TABLES WHERE In_use > 0
    

    You get the locked tables only of the current database.

    0 讨论(0)
  • 2020-11-29 19:42

    You can create your own lock with GET_LOCK(lockName,timeOut)

    If you do a GET_LOCK(lockName, 0) with a 0 time out before you lock the tables and then follow that with a RELEASE_LOCK(lockName) then all other threads performing a GET_LOCK() will get a value of 0 which will tell them that the lock is being held by another thread.

    However this won't work if you don't have all threads calling GET_LOCK() before locking tables. The documentation for locking tables is here

    Hope that helps!

    0 讨论(0)
提交回复
热议问题