Last active
August 29, 2015 14:02
-
-
Save AfonsoTsukamoto/8729e0fe6a5391202dcc to your computer and use it in GitHub Desktop.
[Ruby] Avoid &block in ruby (performance)
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
## | |
# This module uses &Proc.new and yield as a way to prevent passing blocks. | |
# Not tested, as included in another module, changed for gist reasons. | |
module Semaphore | |
class << self | |
attr_accessor :cluster_semaphore | |
attr_accessor :selector_semaphore | |
attr_accessor :tagging_semaphore | |
def init_semaphore | |
Mutex.new | |
end | |
def cluster | |
cluster_semaphore ||= init_semaphore | |
end | |
def selector | |
selector_semaphore ||= init_semaphore | |
end | |
def tagging | |
tagging_semaphore ||= init_semaphore | |
end | |
def included(base) | |
base.send :include, InstanceMethods | |
end | |
end | |
module InstanceMethods | |
def cluster_semaphore | |
self.class.cluster | |
end | |
def selector_semaphore | |
self.class.selector | |
end | |
def tagging_semaphore | |
self.class.tagging | |
end | |
## | |
# If a worker dies, other workers must get the lock | |
# This locked call prevents that. | |
def locked_call(type_lock) | |
type_lock.lock | |
begin | |
yield | |
rescue Exception => e | |
type_lock.unlock | |
raise e | |
end | |
type_lock.unlock | |
end | |
def cluster_lock | |
locked_call(cluster_semaphore, &Proc.new) | |
end | |
def selector_lock | |
locked_call(selector_semaphore, &Proc.new) | |
end | |
def tagging_lock | |
locked_call(tagging_semaphore, &Proc.new) | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment