Last active
December 19, 2015 18:38
-
-
Save derekparker/6000289 to your computer and use it in GitHub Desktop.
Script for show and tell for Postgres Advisory Locks
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
require 'active_record' | |
class ObtainerOfLocks | |
class << self | |
def lock_it_up | |
initiate_useless_connection | |
2.times do | |
fork do | |
exclusive { puts 'Lock obtained.' } | |
end | |
end | |
Process.waitall | |
end | |
private | |
def exclusive | |
if obtained_lock? | |
yield | |
sleep 0.5 | |
release_lock | |
end | |
end | |
def obtained_lock? | |
connection.select_value('select pg_try_advisory_lock(1);') == 't' | |
end | |
def release_lock | |
connection.execute 'select pg_advisory_unlock(1);' | |
end | |
def connection | |
ActiveRecord::Base.connection | |
end | |
def initiate_useless_connection | |
ActiveRecord::Base.establish_connection({ | |
adapter: 'postgresql', | |
encoding: 'unicode', | |
database: 'your_db', | |
pool: 5, | |
timeout: 5000, | |
username: 'username' | |
}) | |
end | |
end | |
end | |
ObtainerOfLocks.lock_it_up |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment