Skip to content

Instantly share code, notes, and snippets.

@steelThread
Last active December 20, 2015 01:39
Show Gist options
  • Save steelThread/6050210 to your computer and use it in GitHub Desktop.
Save steelThread/6050210 to your computer and use it in GitHub Desktop.
SynchronousQueue - Producer-Consumer
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