Skip to content

Instantly share code, notes, and snippets.

@tomykaira
Created July 15, 2016 08:31
Show Gist options
  • Save tomykaira/e6a2a8c75e36b060bbc68ef1b00927f8 to your computer and use it in GitHub Desktop.
Save tomykaira/e6a2a8c75e36b060bbc68ef1b00927f8 to your computer and use it in GitHub Desktop.
Fork safe connection pool in Ruby. Not elegant.
require 'connection_pool'
def open_pool
pool = ConnectionPool.new { File.open('/dev/null', 'r') }
class << pool
def fileno
with { |fd| fd.fileno }
end
end
pool
end
$global_pool = open_pool
module RenewConnectionFork
def fork(&b)
v = super() do
$global_pool = open_pool
b.call
end
end
end
class Object
prepend RenewConnectionFork
end
puts "#{Process.pid}global: #{$global_pool.fileno}"
fork do
puts "#{Process.pid} global: #{$global_pool.fileno}"
end
sleep 1
puts "#{Process.pid}global: #{$global_pool.fileno}"
#--output
# 43873global: 7
# 43886 global: 10
# 43873global: 7
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment