Skip to content

Instantly share code, notes, and snippets.

@samaaron
Last active December 22, 2015 17:59
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save samaaron/6509442 to your computer and use it in GitHub Desktop.
Save samaaron/6509442 to your computer and use it in GitHub Desktop.
Simple Promise implementation in Ruby
require 'thread'
module SonicPi
class Promise
def initialize
@val_sem = Mutex.new
@push_sem = Mutex.new
@box = Queue.new
@value = nil
@delivered = false
@pushed = false
end
def get
return @value if @delivered
@val_sem.synchronize do
return @value if @delivered
val = @box.pop
@value = val
@delivered = true
val
end
end
def deliver!(val)
@push_sem.synchronize do
if(@box.empty? && !@pushed)
@box.push val
@pushed = true
else
raise "Promise already delivered"
end
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment