Last active
May 11, 2019 13:08
-
-
Save dkinzer/98e78a71c588a024a85dfc5a6d1c95c6 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
require "thread" | |
class Delay | |
def initialize(&thunk) | |
@semaphore = Mutex.new | |
@thunk = thunk | |
@evaluated = false | |
end | |
def value | |
synchronize { | |
if @evaluated | |
@value | |
else | |
@value = @thunk.call and @thunk = nil | |
@evaluated = true | |
freeze and @value | |
end | |
} | |
end | |
private | |
def synchronize | |
if @evaluated | |
yield | |
else | |
@semaphore.synchronize { yield } | |
end | |
end | |
end | |
sum = Delay.new { sleep(1); 2 + 5 } | |
(0...1000).map { Thread.new { puts sum.value } } | |
.map(&:join) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Awesome job!