require 'monitor' class Module def synchronize_method *methods methods.each do |method| als = "sync_#{escape_method(method)}" raise "Can't synchronize the '#{method}' twice!" if instance_methods.include?(als) alias_method als, method script = "\ def #{method} *p, &b @monitor ||= Monitor.new @monitor.synchronize{#{als} *p, &b} end" class_eval script, __FILE__, __LINE__ end end def synchronize_all_methods include_super = false methods = self.instance_methods(include_super).collect{|m| m.to_sym} synchronize_method *methods end end