Created
June 26, 2018 16:39
-
-
Save felipeelias/3bb328bf36e1750a2426bc34a45951db 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
# threads dying on fork examples. run with: | |
# ruby main.rb | |
# or | |
# ruby main.rb fork | |
# | |
require 'thread' | |
class Worker | |
def initialize | |
@thread = Thread.new { work } | |
@queue = Queue.new | |
end | |
def push(work) | |
puts "[w] Is it alive? #{ @thread.alive? }" | |
@queue << work | |
end | |
def work | |
loop do | |
puts "[w] Waiting for work..." | |
work = @queue.pop | |
break if work == :shutdown | |
puts "[w] Working #{ work }" | |
end | |
puts "[w] Shut down!" | |
end | |
def shutdown! | |
push(:shutdown) | |
end | |
end | |
def main(worker) | |
puts "[p] Forking..." | |
sleep 5 | |
puts "[p] Pushing..." | |
worker.push "work-1" | |
sleep 5 | |
puts "[p] Pushing..." | |
worker.push "work-2" | |
sleep 5 | |
puts "[p] Shutting down..." | |
worker.shutdown! | |
sleep 5 | |
puts "[p] End!" | |
end | |
worker = Worker.new | |
if ARGV.first == "fork" | |
puts "FORK TEST" | |
fork { main(worker) } | |
Process.waitall | |
else | |
puts "REGULAR TEST" | |
main(worker) | |
end |
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
~/P/f/thread-fork $ ruby main.rb fork | |
FORK TEST | |
[w] Waiting for work... | |
[p] Forking... | |
[p] Pushing... | |
[w] Is it alive? false | |
[p] Pushing... | |
[w] Is it alive? false | |
[p] Shutting down... | |
[w] Is it alive? false | |
[p] End! | |
~/P/f/thread-fork $ ruby main.rb | |
REGULAR TEST | |
[p] Forking... | |
[w] Waiting for work... | |
[p] Pushing... | |
[w] Is it alive? true | |
[w] Working work-1 | |
[w] Waiting for work... | |
[p] Pushing... | |
[w] Is it alive? true | |
[w] Working work-2 | |
[w] Waiting for work... | |
[p] Shutting down... | |
[w] Is it alive? true | |
[w] Shut down! | |
[p] End! |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment