Last active
August 29, 2015 14:03
-
-
Save jqr/8ae0f27a8d5fdeade2a2 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 "thread" | |
# This is an example of how to use popen in a nonblocking fashion while | |
# consuming the output and manipulating it slightly. Additionally it ensures | |
# that the output maintains some consistency even with interleaving writes. | |
# Make a mutex so that we only let one thing write to stdout at a time | |
@stdout_mutex = Mutex.new | |
# A version of puts which shows some debug information, handy for showing off | |
# some thread stuff. | |
def debug_puts(message) | |
safe_puts "%20s %10i %s" % [Thread.current, Time.now.to_i, message] | |
end | |
# A version of puts that will not intermingle output with other threads. | |
def safe_puts(message) | |
@stdout_mutex.synchronize do # will wait if another thread is already executing | |
puts message | |
end | |
end | |
# Open a new thread, save it, and run a long running command. | |
process_thread = Thread.new do | |
IO.popen("echo hello; sleep 10; echo goodbye") do |process| | |
debug_puts process.gets | |
debug_puts process.gets | |
end | |
end | |
# Do normal main thread stuff! | |
debug_puts "Main thread doing it's thang!" | |
sleep 1 | |
# How to wait for the thread to end on it's own | |
debug_puts "Ok, Main thread all done, I want to wait until child thread is ready..." | |
process_thread.join | |
debug_puts "Everyone is done" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment