Skip to content

Instantly share code, notes, and snippets.

@derekparker
Last active December 19, 2015 18:38
Show Gist options
  • Save derekparker/6000289 to your computer and use it in GitHub Desktop.
Save derekparker/6000289 to your computer and use it in GitHub Desktop.
Script for show and tell for Postgres Advisory Locks
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