Last active
December 15, 2020 12:10
-
-
Save kamipo/0bb4e37d58ba18a8cefb8aa02f778231 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# frozen_string_literal: true | |
require "mysql2" | |
def client | |
Mysql2::Client.new( | |
host: "localhost", | |
username: "root", | |
database: "test", | |
) | |
end | |
c1 = client | |
c2 = client | |
c1.query("DROP TABLE IF EXISTS `user_tables`") | |
c1.query <<-SQL | |
CREATE TABLE `user_tables` ( | |
`id` int(11) NOT NULL AUTO_INCREMENT, | |
`name` varchar(255) NOT NULL, | |
PRIMARY KEY (`id`), | |
UNIQUE KEY `index_user_tables_on_name` (`name`) | |
) | |
SQL | |
1000.downto(1) do |i| | |
c1.query("INSERT INTO `user_tables` (`name`) VALUES ('p#{i}')") | |
end | |
t = Thread.new do | |
100.times do |j| | |
c2.query("BEGIN") | |
#puts "c2 locking:#{j}" | |
c2.query("SELECT 1 FROM `user_tables` FORCE INDEX(index_user_tables_on_name) WHERE `name` IN (#{1000.downto(1).map{|i|"'p#{i}'"}.join(",")}) FOR UPDATE") | |
#puts "c2 locked:#{j}" | |
c2.query("COMMIT") | |
end | |
end | |
100.times do |j| | |
c1.query("BEGIN") | |
#puts "c1 locking:#{j}" | |
c1.query("SELECT 1 FROM `user_tables` FORCE INDEX(PRIMARY) WHERE `id` IN (#{1.upto(1000).to_a.join(",")}) FOR UPDATE") | |
#puts "c1 locked:#{j}" | |
c1.query("COMMIT") | |
end | |
t.join |
Author
kamipo
commented
Dec 11, 2019
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment