-
-
Save havenwood/c599b9d2b8e99e7edc849ef20ec9032e to your computer and use it in GitHub Desktop.
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
@cached_value = nil | |
@value_cached = false | |
@mutex = Mutex.new | |
def expensive_calculation | |
sleep 5 | |
42 | |
end | |
def foo | |
return @cached_value if @value_cached | |
@mutex.synchronize do | |
return @cached_value if @value_cached | |
@cached_value = expensive_calculation | |
@value_cached = true | |
return @cached_value | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment