Skip to content

Instantly share code, notes, and snippets.

@nobuoka
Created August 15, 2011 09:55
Show Gist options
  • Save nobuoka/1145979 to your computer and use it in GitHub Desktop.
Save nobuoka/1145979 to your computer and use it in GitHub Desktop.
require 'pg'
# 接続先 DB の情報
DB_S_ARRAY = [ 'localhost', 5432, '', '', 'db_name', 'user_name', 'password' ]
# テーブル table_name に対して先にロックを獲得するスレッド
t1 = Thread.new do
dbconn = PGconn.connect( *DB_S_ARRAY )
dbconn.transaction do
puts 'locking table... (t1)'
dbconn.exec( 'LOCK TABLE table_name IN EXCLUSIVE MODE' ){}
puts 'locked table!! (t1)'
# ロック獲得後, スレッド t2 がロックを獲得しようとするまで待つ
sleep 3
end
puts 'unlocked table!! (t1)'
end
sleep 1
# テーブル table_name に対して後からロックを獲得しようとするスレッド
t2 = Thread.new do
dbconn = PGconn.connect( *DB_S_ARRAY )
dbconn.transaction do
puts 'locking table... (t2)'
# この関数の中でずっと待ち状態になってしまってデッドロック
dbconn.exec( 'LOCK TABLE table_name IN EXCLUSIVE MODE' ){}
puts 'locked table!! (t2)'
end
puts 'unlocked table!! (t2)'
end
t1.join()
t2.join()
# --- output (ruby 1.9.2) ---
# locking table... (t1)
# locked table!! (t1)
# locking table... (t2)
# (これ以降処理が進まない)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment