Created
May 8, 2017 12:51
-
-
Save jhonylucas74/21625ff35a514c3962c33a3305ce4ac7 to your computer and use it in GitHub Desktop.
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
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