Skip to content

Instantly share code, notes, and snippets.

@edbond
Last active August 29, 2015 13:56
Show Gist options
  • Save edbond/8861530 to your computer and use it in GitHub Desktop.
Save edbond/8861530 to your computer and use it in GitHub Desktop.
require 'thread'
class Channel
def initialize
@q = Queue.new
end
def put! val
@q << val
self
end
def receive
@q.pop
end
def take!
yield @q.pop
end
end
def go_loop &block
l = Proc.new do
loop { yield }
end
Thread.new(&l).tap do |t|
t.run
end
end
def channel
Channel.new
end
def consumer chan
go_loop do
v = chan.receive
chan.put! "#{v} \o/"
end
end
def producer chan
chan.put! 42
chan.put! "string"
end
chan = channel()
# consumer chan
producer chan
2.times {
chan.take! { |v| puts "GOT value: #{v.inspect}"}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment