Last active
August 29, 2015 13:56
-
-
Save edbond/8861530 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 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