created Redistat::Synchronize mixin to help with thread-safety

This commit is contained in:
2011-04-15 14:03:26 +01:00
parent 0a7abe935e
commit 5d92c1dbae
3 changed files with 125 additions and 0 deletions

View File

@@ -3,6 +3,7 @@ require 'rubygems'
require 'date'
require 'time'
require 'digest/sha1'
require 'monitor'
# Active Support 2.x or 3.x
require 'active_support'
@@ -16,6 +17,7 @@ require 'redis'
require 'json'
require 'redistat/options'
require 'redistat/synchronize'
require 'redistat/connection'
require 'redistat/database'
require 'redistat/collection'
@@ -47,6 +49,14 @@ module Redistat
class << self
def thread_safe
Synchronize.thread_safe
end
def thread_safe=(value)
Synchronize.thread_safe = value
end
def connection(ref = nil)
Connection.get(ref)
end

View File

@@ -0,0 +1,51 @@
require 'monitor'
module Redistat
module Synchronize
class << self
def included(base)
base.send(:include, InstanceMethods)
end
def monitor
@monitor ||= Monitor.new
end
def thread_safe
monitor.synchronize do
@thread_safe ||= false
end
end
def thread_safe=(value)
monitor.synchronize do
@thread_safe = value
end
end
end # << self
module InstanceMethods
def thread_safe
Synchronize.thread_safe
end
def thread_safe=(value)
Synchronize.thread_safe = value
end
def monitor
Synchronize.monitor
end
def synchronize(&block)
if thread_safe
monitor.synchronize(&block)
else
block.call
end
end
end # InstanceMethods
end
end