lib/thread/delay.rb in thread-0.0.3 vs lib/thread/delay.rb in thread-0.0.4

- old
+ new

@@ -9,27 +9,36 @@ #++ # A delay is an object that incapsulates a block which is called upon # value retrieval, and its result cached. class Thread::Delay + # Create a delay with the passed block. def initialize (&block) + @mutex = Mutex.new + @block = block end # Check if an exception has been raised. def exception? - instance_variable_defined? :@exception + @mutex.synchronize { + instance_variable_defined? :@exception + } end # Return the raised exception. def exception - @exception + @mutex.synchronize { + @exception + } end # Check if the delay has been called. def delivered? - instance_variable_defined? :@value + @mutex.synchronize { + instance_variable_defined? :@value + } end alias realized? delivered? # Get the value of the delay, if it's already been executed, return the @@ -40,16 +49,18 @@ def value raise @exception if exception? return @value if realized? - begin - @value = @block.call - rescue Exception => e - @exception = e + @mutex.synchronize { + begin + @value = @block.call + rescue Exception => e + @exception = e - raise - end + raise + end + } end alias ~ value # Do the same as {#value}, but return nil in case of exception.