Skip to content

Instantly share code, notes, and snippets.

@dkinzer
Last active May 11, 2019 13:08
Show Gist options
  • Save dkinzer/98e78a71c588a024a85dfc5a6d1c95c6 to your computer and use it in GitHub Desktop.
Save dkinzer/98e78a71c588a024a85dfc5a6d1c95c6 to your computer and use it in GitHub Desktop.
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)
@ericnormand
Copy link

Awesome job!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment