Skip to content

Instantly share code, notes, and snippets.

@jhonylucas74
Created May 8, 2017 12:51
Show Gist options
  • Save jhonylucas74/21625ff35a514c3962c33a3305ce4ac7 to your computer and use it in GitHub Desktop.
Save jhonylucas74/21625ff35a514c3962c33a3305ce4ac7 to your computer and use it in GitHub Desktop.
require 'colorize'
require 'thread'
$semaphore = Mutex.new
$phore = Mutex.new
$buffer = []
$cv = ConditionVariable.new
class Consumidor
def run
while true do
$semaphore.synchronize {
if $buffer.length > 0 then
$buffer.pop
else
$cv.signal
$cv.wait($semaphore)
end
print "#{$buffer.length}".blue
}
end
end
end
class Produtor
def run
while true do
$semaphore.synchronize {
if $buffer.length < 19 then
$buffer << rand(100)
else
$cv.signal
$cv.wait($semaphore)
end
print "#{$buffer.length}"
}
end
end
end
threads = []
threads << Thread.new { new Consumidor.new.run }
threads << Thread.new { new Produtor.new.run }
# executando threads
threads.each(&:join)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment