Deadlock error in INSERT statement

前端 未结 4 1234
别跟我提以往
别跟我提以往 2021-02-12 22:29

We\'ve got a web-based application. There are time-bound database operations (INSERTs and UPDATEs) in the application which take more time to complete, hence this particular fl

4条回答
  •  闹比i
    闹比i (楼主)
    2021-02-12 22:45

    Deadlock explained:
    In a nutshell, what is happening is that a particular SQL statement (INSERT or other) is waiting on another statement to release a lock on a particular part of the database, before it can proceed. Until this lock is released, the first SQL statement, call it "statement A" will not allow itself to access this part of the database to do its job (= regular lock situation). But... statement A has also put a lock on another part of the database to ensure that no other users of the database access (for reading, or modifiying/deleting, depending on the type of lock). Now... the second SQL statement, is itself in need of accessing the data section marked by the lock of Statement A. That is a DEAD LOCK : both Statement will wait, ad infinitum, on one another.

    The remedy...

    This would require to know the specific SQL statement these various threads are running, and looking in there if there is a way to either:

    a) removing some of the locks, or changing their types.
       For example, maybe the whole table is locked, whereby only a given row, or
       a page thereof would be necessary.
    b) preventing multiple of these queries to be submitted at a given time.
       This would be done by way of semaphores/locks (aka MUTEX) at the level of the
       multi-threading logic.
    

    Beware that the "b)" approach, if not correctly implemented may just move the deadlock situation from within SQL to within the program/threads logic. The key would be to only create one mutex to be obtained first by any thread which is about to run one of these deadlock-prone queries.

提交回复
热议问题