Last active
April 19, 2016 06:47
-
-
Save ursm/dcd49c76d358bb6bbdba 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
=begin | |
$ export PGUSER=<your_pg_user> | |
$ createdb foo | |
$ bundle | |
$ ruby foo.rb | |
=end | |
require 'bundler/setup' | |
require 'logger' | |
require 'sequel' | |
require 'timeout' | |
logdev = '/dev/null' # or $stdout | |
conn1 = Sequel.connect('postgres:///foo', loggers: [Logger.new(logdev).tap {|l| l.progname = 'conn1' }]) | |
conn2 = Sequel.connect('postgres:///foo', loggers: [Logger.new(logdev).tap {|l| l.progname = 'conn2' }]) | |
conn1.create_table? :t | |
at_exit do | |
conn1.drop_table :t | |
end | |
t1 = conn1[:t] | |
t2 = conn2[:t] | |
puts '# transaction (read comitted)' | |
conn1.transaction do | |
p [t1.count, t2.count] #=> [0, 0] | |
t1.insert | |
p [t1.count, t2.count] #=> [1, 0] | |
end | |
t1.truncate | |
puts '-' * 30 | |
puts | |
puts '# transaction (serializable)' | |
conn1.transaction isolation: :serializable do | |
p [t1.count, t2.count] #=> [0, 0] | |
t1.insert | |
p [t1.count, t2.count] #=> [1, 0] | |
end | |
t1.truncate | |
puts '-' * 30 | |
puts | |
puts '# table-level locks (access exclusive)' | |
t1.lock 'ACCESS EXCLUSIVE' do | |
puts 'begin lock' | |
# 同一スレッド、同一コネクションからは参照できる | |
puts "conn1: #{t1.count}" | |
# 別コネクションからの参照はロック開放までブロックされる | |
begin | |
Timeout.timeout 1 do | |
puts "conn2: #{t2.count}" | |
end | |
rescue Timeout::Error | |
puts 'conn2: blocked' | |
end | |
# 別スレッドからの参照はロック開放までブロックされる | |
Thread.new { puts "conn1 (another thread): #{t1.count}" } | |
Thread.new { puts "conn2 (another thread): #{t2.count}" } | |
t1.insert | |
puts "conn1: #{t1.count}" | |
end | |
puts 'end lock' | |
sleep 1 |
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
source 'https://rubygems.org' | |
gem 'pg' | |
gem 'sequel' |
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
$ ruby foo.rb | |
# transaction (read comitted) | |
[0, 0] | |
[1, 0] | |
------------------------------ | |
# transaction (serializable) | |
[0, 0] | |
[1, 0] | |
------------------------------ | |
# table-level locks (access exclusive) | |
begin lock | |
conn1: 0 | |
conn2: blocked | |
conn1: 1 | |
end lock | |
conn2 (another thread): 1 | |
conn1 (another thread): 1 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment