MySQL is adding more tools to monitor its internals with every new release, but one thing it still lacks is a way to find out who is locking what, and therefore which transactions block which other ones. This is such a vital feature that I’m considering writing my own patch to the source! Still, it is possible, to a limited extent, to find out who’s locking resources. In this article I’ll explain how you can do that.
This article is the second in a series on how to use the innotop MySQL and InnoDB monitor.
Introduction
Here’s the situation: you are trying to update a table and every time you issue the query, it hangs until it times out and tells you the lock wait timeout was exceeded. Someone has locked the table you’re trying to update, but you have no idea who. This can be incredibly frustrating, because this could go on indefinitely. I’ve sometimes had to put work off till another day, because the table is locked all day long.
I’ve found only a very limited set of circumstances in which MySQL will say what’s happening with locks. These are all printed out in the text of SHOW ENGINE INNODB STATUS.
When there was a deadlock
The first way to see locks is when there’s been a deadlock. The status text will show transaction information on the transactions that deadlocked, which locks they held, and which they were waiting for. Here is a sample. Look at the sections titled “WAITING FOR THIS LOCK TO BE GRANTED” and “HOLDS THE LOCKS.”
------------------------LATEST DETECTED DEADLOCK------------------------060731 20:19:58*** (1) TRANSACTION:TRANSACTION 0 93698, ACTIVE 2 sec, process no 12767, OS thread id 1141946720 starting index readmysql tables in use 1, locked 1LOCK WAIT 4 lock struct(s), heap size 1216MySQL thread id 3, query id 19 localhost root Updatingupdate test.innodb_deadlock_maker set a = 0 where a <> 0*** (1) WAITING FOR THIS LOCK TO BE GRANTED:RECORD LOCKS space id 0 page no 131120 n bits 72 index `GEN_CLUST_INDEX` of table `test/innodb_deadlock_maker` trx id 0 93698 lock_mode X waitingRecord lock, heap no 2 PHYSICAL RECORD: n_fields 4; compact format; info bits 0 0: len 6; hex 000000019000; asc ;; 1: len 6; hex 000000016e01; asc n ;; 2: len 7; hex 80000000320110; asc 2 ;; 3: len 4; hex 80000000; asc ;;*** (2) TRANSACTION:TRANSACTION 0 93699, ACTIVE 2 sec, process no 12767, OS thread id 1142212960 starting index read, thread declared inside InnoDB 500mysql tables in use 1, locked 14 lock struct(s), heap size 1216MySQL thread id 4, query id 20 localhost root Updatingupdate test.innodb_deadlock_maker set a = 1 where a <> 1*** (2) HOLDS THE LOCK(S):RECORD LOCKS space id 0 page no 131120 n bits 72 index `GEN_CLUST_INDEX` of table `test/innodb_deadlock_maker` trx id 0 93699 lock mode SRecord lock, heap no 1 PHYSICAL RECORD: n_fields 1; compact format; info bits 0 0: len 8; hex 73757072656d756d; asc supremum;;Record lock, heap no 2 PHYSICAL RECORD: n_fields 4; compact format; info bits 0 0: len 6; hex 000000019000; asc ;; 1: len 6; hex 000000016e01; asc n ;; 2: len 7; hex 80000000320110; asc 2 ;; 3: len 4; hex 80000000; asc ;;Record lock, heap no 3 PHYSICAL RECORD: n_fields 4; compact format; info bits 0 0: len 6; hex 000000019001; asc ;; 1: len 6; hex 000000016e01; asc n ;; 2: len 7; hex 8000000032011f; asc 2 ;; 3: len 4; hex 80000001; asc ;;*** (2) WAITING FOR THIS LOCK TO BE GRANTED:RECORD LOCKS space id 0 page no 131120 n bits 72 index `GEN_CLUST_INDEX` of table `test/innodb_deadlock_maker` trx id 0 93699 lock_mode X waitingRecord lock, heap no 2 PHYSICAL RECORD: n_fields 4; compact format; info bits 0 0: len 6; hex 000000019000; asc ;; 1: len 6; hex 000000016e01; asc n ;; 2: len 7; hex 80000000320110; asc 2 ;; 3: len 4; hex 80000000; asc ;;*** WE ROLL BACK TRANSACTION (2)
More importantly, the lines beginning “RECORD LOCKS space id 0″ show which index of which table was locked. That is the real meat of the matter — that’s what you need to know.
There’s just one problem: after there’s been a deadlock, it’s too late. You don’t want to know what held locks in the past, you want to know what holds them now. The deadlock information isn’t usually helpful in finding out what transaction is blocking something from happening.
When a transaction is waiting for locks
The next place you can sometimes see lock information is in the transaction section of the output. Here’s a sample:
---TRANSACTION 0 93789802, ACTIVE 19 sec, process no 9544, OS thread id 389120018MySQL thread id 23740, query id 194861248 worker1.office 192.168.0.12 robot---TRANSACTION 0 93789797, ACTIVE 20 sec, process no 9537, OS thread id 389005359 starting index readmysql tables in use 1, locked 1LOCK WAIT 2 lock struct(s), heap size 320MySQL thread id 23733, query id 194861215 elpaso 192.168.0.31 robot Updatingupdate test.test set col1 = 4------- TRX HAS BEEN WAITING 20 SEC FOR THIS LOCK TO BE GRANTED:RECORD LOCKS space id 0 page no 299998 n bits 200 index `PRIMARY` of table `test/test` trx id 0 93789797 lock_mode X locks rec but not gap waitingRecord lock, heap no 77 PHYSICAL RECORD: n_fields 15; compact format; info bits 0 0: len 4; hex 80474fd6; asc GO ;; 1: len 6; hex 000005970680; asc ;; 2: len 7; hex 000017c02b176c; asc + l;; 3: len 4; hex 80000003; asc ;; 4: len 8; hex 800000000da0c93a; asc :;; 5: len 8; hex 800000000eb2ea7e; asc ~;; 6: len 4; hex c771fe44; asc q D;; 7: len 4; hex 8000003e; asc >;; 8: len 8; hex 8000123eb9e5dfd5; asc > ;; 9: len 4; hex 8000003a; asc :;; 10: len 8; hex 8000123eb9e43603; asc > 6 ;; 11: len 4; hex 80000035; asc 5;; 12: len 8; hex 8000123eb9d6c130; asc > 0;; 13: len 4; hex 80000033; asc 3;; 14: len 8; hex 8000123eb9c7c853; asc > S;; ------------------------TRANSACTION 0 93789679, ACTIVE 31082 sec, process no 9535, OS thread id 388972583 starting index read, thread declared inside InnoDB 6mysql tables in use 4, locked 411614 lock struct(s), heap size 683328MySQL thread id 23731, query id 194861117 elpaso 192.168.0.31 robot
Notice the first transaction has been waiting 20 seconds for a lock to be granted, and it tells you which table and index as above. The other transaction I included (there were many in this section, but I omitted most) says it has 4 tables open and 4 locked. What it doesn’t say is which ones.
Again, there’s some information here, but not a lot. If you issue a query and it hangs and waits for a lock, knowing what lock it’s waiting for isn’t really helpful. And knowing some other transaction holds a lock isn’talways helpful either.
It can be useful sometimes though, and that’s better than nothing. If you only see two transactions with locks, you know the one that’s not waiting for a lock is probably the one that holds them. Notice something scary in the information above? Transaction “0 93789771″, on connection 23731, has been active for… eight and a half hours! Whoa. It’s time to find out what owns that connection and possibly kill it.
The take-away here is, if you’re getting blocked on an InnoDB table, and you’re lucky enough to see only one other transaction with locks, it’s probably the one blocking you.
What about table locks?
Ah, good question. What if the table isn’t InnoDB, or what if someone locked it with LOCK TABLES, and it doesn’t show up in the output of SHOW ENGINE INNODB STATUS? As far as I know, you’re helpless. I don’t know how to get any information on who’s locking the table then. Table lock information doesn’t seem to be exposed in any fashion — only row lock information.
In fact, if you’re in a transaction, LOCK TABLES seems to “kick you out” of the transaction. Try experimenting with START TRANSACTION and LOCK TABLES on an InnoDB table, and you’ll see what I mean. If you lock a table for writing, then try to select from it in another connection, the other connection will block. If you then issueSTART TRANSACTION on the first connection, the second connection will immediately unblock, and the first connection’s transaction will disappear from the InnoDB status text.
Who wants to read all that mess?
Who, indeed? The text I included above is a pain to read, and it’s not even representative of what you’ll really be looking at. For one thing, you might have to scan through 40 or more transactions to find the ones you care about, and then there’s all the other information in the output, some of which can be voluminous (such as deadlocks). What a hassle!
Fortunately, there’s a tool to do that for you: innotop. This tool formats the output neatly and gives you filtering options to display only transactions with locks (or just sort them to the top of the display). Here’s how you can do that:
Start innotop and use the “T” key to enter InnoDB Transaction mode, if it’s not already in that mode. You will see a list of transactions. Next, make the “Locks,” “Tbl Used,” and “Tbl Lck” columns visible. Press the “c” key to activate the “choose columns” dialog:
Press Return and you should see something that looks like this:
Now sort transactions with locks to the top by pressing the “s” key and choosing “lock_structs” as the sort column. You may need to press the “r” key afterwards to reverse the sort order if they go to the bottom instead. Alternatively, you can use the “w” key to add a filter on the “lock_structs” column, such as “[1-9]” to match only rows where the column isn’t zero (this is a handy filter to add in general, just so you can see how many transactions have locks).
Here’s a screenshot of me changing the sort column, and adding a filter:
And here’s a screenshot of the result:
In this example you could see the locks without hiding the other rows, but when you have a very busy server it can really help to hide all the transactions without locks.
Isn’t that easier than digging through the output of SHOW ENGINE INNODB STATUS? I think so.
Is there more?
Though I’ve searched the Internet, searched the source code and the MySQL manual, I haven’t been able to find any other ways to get information on current locks in MySQL. But I’d be delighted if you prove me wrong! If you have anything to add, please comment.
原文地址:http://www.xaprb.com/blog/2006/07/31/how-to-analyze-innodb-mysql-locks/

데이터베이스 및 프로그래밍에서 MySQL의 위치는 매우 중요합니다. 다양한 응용 프로그램 시나리오에서 널리 사용되는 오픈 소스 관계형 데이터베이스 관리 시스템입니다. 1) MySQL은 웹, 모바일 및 엔터프라이즈 레벨 시스템을 지원하는 효율적인 데이터 저장, 조직 및 검색 기능을 제공합니다. 2) 클라이언트 서버 아키텍처를 사용하고 여러 스토리지 엔진 및 인덱스 최적화를 지원합니다. 3) 기본 사용에는 테이블 작성 및 데이터 삽입이 포함되며 고급 사용에는 다중 테이블 조인 및 복잡한 쿼리가 포함됩니다. 4) SQL 구문 오류 및 성능 문제와 같은 자주 묻는 질문은 설명 명령 및 느린 쿼리 로그를 통해 디버깅 할 수 있습니다. 5) 성능 최적화 방법에는 인덱스의 합리적인 사용, 최적화 된 쿼리 및 캐시 사용이 포함됩니다. 모범 사례에는 거래 사용 및 준비된 체계가 포함됩니다

MySQL은 소규모 및 대기업에 적합합니다. 1) 소기업은 고객 정보 저장과 같은 기본 데이터 관리에 MySQL을 사용할 수 있습니다. 2) 대기업은 MySQL을 사용하여 대규모 데이터 및 복잡한 비즈니스 로직을 처리하여 쿼리 성능 및 트랜잭션 처리를 최적화 할 수 있습니다.

InnoDB는 팬텀 읽기를 차세대 점화 메커니즘을 통해 효과적으로 방지합니다. 1) Next-Keylocking은 Row Lock과 Gap Lock을 결합하여 레코드와 간격을 잠그기 위해 새로운 레코드가 삽입되지 않도록합니다. 2) 실제 응용 분야에서 쿼리를 최적화하고 격리 수준을 조정함으로써 잠금 경쟁을 줄이고 동시성 성능을 향상시킬 수 있습니다.

MySQL은 프로그래밍 언어가 아니지만 쿼리 언어 SQL은 프로그래밍 언어의 특성을 가지고 있습니다. 1. SQL은 조건부 판단, 루프 및 가변 작업을 지원합니다. 2. 저장된 절차, 트리거 및 기능을 통해 사용자는 데이터베이스에서 복잡한 논리 작업을 수행 할 수 있습니다.

MySQL은 오픈 소스 관계형 데이터베이스 관리 시스템으로, 주로 데이터를 신속하고 안정적으로 저장하고 검색하는 데 사용됩니다. 작업 원칙에는 클라이언트 요청, 쿼리 해상도, 쿼리 실행 및 반환 결과가 포함됩니다. 사용의 예로는 테이블 작성, 데이터 삽입 및 쿼리 및 조인 작업과 같은 고급 기능이 포함됩니다. 일반적인 오류에는 SQL 구문, 데이터 유형 및 권한이 포함되며 최적화 제안에는 인덱스 사용, 최적화 된 쿼리 및 테이블 분할이 포함됩니다.

MySQL은 데이터 저장, 관리, 쿼리 및 보안에 적합한 오픈 소스 관계형 데이터베이스 관리 시스템입니다. 1. 다양한 운영 체제를 지원하며 웹 응용 프로그램 및 기타 필드에서 널리 사용됩니다. 2. 클라이언트-서버 아키텍처 및 다양한 스토리지 엔진을 통해 MySQL은 데이터를 효율적으로 처리합니다. 3. 기본 사용에는 데이터베이스 및 테이블 작성, 데이터 삽입, 쿼리 및 업데이트가 포함됩니다. 4. 고급 사용에는 복잡한 쿼리 및 저장 프로 시저가 포함됩니다. 5. 설명 진술을 통해 일반적인 오류를 디버깅 할 수 있습니다. 6. 성능 최적화에는 인덱스의 합리적인 사용 및 최적화 된 쿼리 문이 포함됩니다.

MySQL은 성능, 신뢰성, 사용 편의성 및 커뮤니티 지원을 위해 선택됩니다. 1.MYSQL은 효율적인 데이터 저장 및 검색 기능을 제공하여 여러 데이터 유형 및 고급 쿼리 작업을 지원합니다. 2. 고객-서버 아키텍처 및 다중 스토리지 엔진을 채택하여 트랜잭션 및 쿼리 최적화를 지원합니다. 3. 사용하기 쉽고 다양한 운영 체제 및 프로그래밍 언어를 지원합니다. 4. 강력한 지역 사회 지원을 받고 풍부한 자원과 솔루션을 제공합니다.

InnoDB의 잠금 장치에는 공유 잠금 장치, 독점 잠금, 의도 잠금 장치, 레코드 잠금, 갭 잠금 및 다음 키 잠금 장치가 포함됩니다. 1. 공유 잠금을 사용하면 다른 트랜잭션을 읽지 않고 트랜잭션이 데이터를 읽을 수 있습니다. 2. 독점 잠금은 다른 트랜잭션이 데이터를 읽고 수정하는 것을 방지합니다. 3. 의도 잠금은 잠금 효율을 최적화합니다. 4. 레코드 잠금 잠금 인덱스 레코드. 5. 갭 잠금 잠금 장치 색인 기록 간격. 6. 다음 키 잠금은 데이터 일관성을 보장하기 위해 레코드 잠금과 갭 잠금의 조합입니다.


핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

AI Hentai Generator
AI Hentai를 무료로 생성하십시오.

인기 기사

뜨거운 도구

MinGW - Windows용 미니멀리스트 GNU
이 프로젝트는 osdn.net/projects/mingw로 마이그레이션되는 중입니다. 계속해서 그곳에서 우리를 팔로우할 수 있습니다. MinGW: GCC(GNU Compiler Collection)의 기본 Windows 포트로, 기본 Windows 애플리케이션을 구축하기 위한 무료 배포 가능 가져오기 라이브러리 및 헤더 파일로 C99 기능을 지원하는 MSVC 런타임에 대한 확장이 포함되어 있습니다. 모든 MinGW 소프트웨어는 64비트 Windows 플랫폼에서 실행될 수 있습니다.

WebStorm Mac 버전
유용한 JavaScript 개발 도구

SecList
SecLists는 최고의 보안 테스터의 동반자입니다. 보안 평가 시 자주 사용되는 다양한 유형의 목록을 한 곳에 모아 놓은 것입니다. SecLists는 보안 테스터에게 필요할 수 있는 모든 목록을 편리하게 제공하여 보안 테스트를 더욱 효율적이고 생산적으로 만드는 데 도움이 됩니다. 목록 유형에는 사용자 이름, 비밀번호, URL, 퍼징 페이로드, 민감한 데이터 패턴, 웹 셸 등이 포함됩니다. 테스터는 이 저장소를 새로운 테스트 시스템으로 간단히 가져올 수 있으며 필요한 모든 유형의 목록에 액세스할 수 있습니다.

Dreamweaver Mac版
시각적 웹 개발 도구

안전한 시험 브라우저
안전한 시험 브라우저는 온라인 시험을 안전하게 치르기 위한 보안 브라우저 환경입니다. 이 소프트웨어는 모든 컴퓨터를 안전한 워크스테이션으로 바꿔줍니다. 이는 모든 유틸리티에 대한 액세스를 제어하고 학생들이 승인되지 않은 리소스를 사용하는 것을 방지합니다.
