本文共 3032 字,大约阅读时间需要 10 分钟。
Deadlocks, in general, are a fascinating yet challenging technical problem that most DBAs and developers encounter during their careers. This article will walk through a series of case studies to help those interested better understand deadlocks in MySQL environments.
A development team encountered a deadlock issue while initializing data. Their approach involved batch inserting multiple records into a table with a unique constraint. The unique constraint caused deadlocks due to adjacent values being inserted in sequence.
The table tc has the following structure:
CREATE TABLE `tc` ( `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT '自增ID', `c1` bigint(20) unsigned NOT NULL DEFAULT '0', `c2` bigint(20) unsigned NOT NULL DEFAULT '0', `c3` bigint(20) unsigned NOT NULL DEFAULT '0', `c4` tinyint(4) NOT NULL DEFAULT '0', `c5` tinyint(4) NOT NULL DEFAULT '0', `created_at` datetime NOT NULL DEFAULT '1970-01-01 08:00:00', `deleted_at` datetime NOT NULL DEFAULT '1970-01-01 08:00:00', PRIMARY KEY (`id`), UNIQUE KEY `uniq_cid_bid_dt_tid` (`c1`, `c2`, `deleted_at`, `c3`), ENGINE=InnoDB AUTO_INCREMENT=19 DEFAULT CHARSET=utf8mb4)
The deadlock log reveals the following:
c1 and c2 values but different c3 values.Deadlocks caused by concurrent inserts can be challenging to resolve at the SQL level. However, some strategies include:
The deadlock in this case arises from concurrent inserts of adjacent records due to unique constraints. The system's lock mechanisms, particularly the Next-Key Lock, create a cycle of waiting transactions, leading to deadlock.
For further understanding of MySQL deadlocks and lock mechanisms, we recommend exploring:
转载地址:http://qpn.baihongyu.com/