Last active
December 20, 2015 01:39
-
-
Save steelThread/6050210 to your computer and use it in GitHub Desktop.
SynchronousQueue - Producer-Consumer
This file contains hidden or 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
import java.util.concurrent.SynchronousQueue | |
module ProducerConsumer | |
def self.do_work | |
trap :TERM , -> { Queue.shutdown! } | |
trap :INT , -> { Queue.shutdown! } | |
threads = [ | |
Producer.new.tap{ |o| o.start }, | |
Consumer.new.tap{ |o| o.start } | |
] | |
threads.each &:join | |
puts 'Buh Bye' | |
end | |
module Queue | |
@running = true | |
def self.put(work) | |
_queue.put work if running? | |
end | |
def self.take | |
_queue.take if running? | |
end | |
def self.running? | |
@running | |
end | |
def self.shutdown! | |
puts 'shutting down' | |
@running = false | |
drain | |
end | |
private | |
def self._queue | |
@queue ||= SynchronousQueue.new | |
end | |
def self.drain | |
_queue.take | |
end | |
end | |
class Producer < java.lang.Thread | |
def run | |
while Queue.running? do | |
puts 'produce' | |
Queue.put 'work' | |
sleep 0.1 | |
end | |
end | |
end | |
class Consumer < java.lang.Thread | |
def run | |
while Queue.running? do | |
puts "working on #{Queue.take}" | |
sleep 1 | |
end | |
end | |
end | |
end | |
ProducerConsumer.do_work |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment