|
|||
Previous < |
Contents ^
|
Next >
|
require 'net/http' pages = %w( www.rubycentral.com www.awl.com www.pragmaticprogrammer.com ) threads = [] for page in pages threads << Thread.new(page) { |myPage| h = Net::HTTP.new(myPage, 80) puts "Fetching: #{myPage}" resp, data = h.get('/', nil ) puts "Got #{myPage}: #{resp.message}" } end threads.each { |aThread| aThread.join } |
|
Fetching: www.rubycentral.com Fetching: www.awl.com Fetching: www.pragmaticprogrammer.com Got www.rubycentral.com: OK Got www.pragmaticprogrammer.com: OK Got www.awl.com: OK |
Thread.new
call. It is given a
block that contains the code to be run in a new thread. In our case,
the block uses the net/http
library to fetch the top page from
each of our nominated sites. Our tracing clearly shows that these
fetches are going on in parallel.
When we create the thread, we pass the required HTML page in as a
parameter. This parameter is passed on to the block as myPage
.
Why do we do this, rather than simply using the value of the variable
page
within the block?
A thread shares all global, instance, and local variables that are in
existence at the time the thread starts.
As anyone with a kid brother
can tell you, sharing isn't always a good thing. In this case, all
three threads would share the variable page
. The first thread
gets started, and page
is set to http://www.rubycentral.com. In
the meantime, the loop creating the threads is still running. The
second time around, page
gets set to http://www.awl.com. If the
first thread has not yet finished using the page
variable, it
will suddenly start using its new value. These bugs are difficult to
track down.
However, local variables created within a thread's block are truly
local to that thread---each thread will have its own copy of these
variables. In our case, the variable myPage
will be set at the
time the thread is created, and each thread will have its own copy of
the page address.
join
on each of the threads we created?
When a Ruby program terminates, all running threads are killed,
regardless of their states. However, you can wait for a particular
thread to finish by calling that thread's
Thread#join
method.
The calling thread will block until the given thread is finished. By
calling join
on each of the requestor threads, you can make
sure that all three requests have completed before you terminate the
main program.
In addition to join
, there are a few other handy routines that are
used to manipulate threads. First of all, the current thread is
always accessible using
Thread.current
. You can obtain a list
of all threads using
Thread.list
, which returns a list of
all Thread
objects that are runnable or stopped. To determine the
status of a particular thread, you can use
Thread#status
and
Thread#alive?
.
Also, you can adjust the priority of a thread using
Thread#priority=
. Higher-priority threads will run before
lower-priority threads. We'll talk more about thread scheduling, and
stopping and starting threads, in just a bit.
Thread
features a
special facility that allows thread-local variables to be created and
accessed by name. You simply treat the thread object as if it were a
Hash
, writing to elements using []=
and reading them back
using []
. In this example, each thread records the current
value of the variable count
in a thread-local variable with the
key mycount
. (There's a race condition in this code, but we haven't
talked about synchronization yet, so we'll just quietly ignore it for now.)
count = 0 arr = [] 10.times do |i| arr[i] = Thread.new { sleep(rand(0)/10.0) Thread.current["mycount"] = count count += 1 } end arr.each {|t| t.join; print t["mycount"], ", " } puts "count = #{count}" |
8, 0, 3, 7, 2, 1, 6, 5, 4, 9, count = 10 |
count
captured by each. Just to make it more
interesting, we have each thread wait a random time before recording
the value.
abort_on_exception
is false
, the default
condition, an unhandled exception simply kills the current
thread---all the rest continue to run. In the following example,
thread number 3 blows up and fails to produce any output. However,
you can still see the trace from the other threads.
threads = [] 6.times { |i| threads << Thread.new(i) { raise "Boom!" if i == 3 puts i } } threads.each {|t| t.join } |
01 2 45prog.rb:4: Boom! (RuntimeError) from prog.rb:8:in `join' from prog.rb:8 from prog.rb:8:in `each' from prog.rb:8 |
abort_on_exception
to true
, and an
unhandled exception kills all running threads. Once thread 3 dies,
no more output is produced.
Thread.abort_on_exception = true threads = [] 6.times { |i| threads << Thread.new(i) { raise "Boom!" if i == 3 puts i } } threads.each {|t| t.join } |
01 2 prog.rb:5: Boom! (RuntimeError) from prog.rb:7:in `initialize' from prog.rb:7:in `new' from prog.rb:7 from prog.rb:3:in `times' from prog.rb:3 |
Thread
provides a number of methods to control the thread
scheduler. Invoking
Thread.stop
stops the current thread, while
Thread#run
arranges for a particular thread to be
run.
Thread.pass
deschedules the current thread, allowing others
to run, and
Thread#join
and
Thread#value
suspend the
calling thread until a given thread finishes.
We can demonstrate these features in the following, totally pointless
program.
t = Thread.new { sleep .1; Thread.pass; Thread.stop; }
|
||
t.status
|
» |
"sleep"
|
t.run
|
||
t.status
|
» |
"run"
|
t.run
|
||
t.status
|
» |
false
|
true
(using the
Thread.critical=
method),
the scheduler will not schedule any
existing thread to run.
However, this does not block new threads from
being created and run. Certain thread operations (such as stopping or
killing a thread, sleeping in the current thread, or raising an
exception) may cause a thread to be scheduled even when in a critical
section.
Using
Thread.critical=
directly is certainly possible, but it
isn't terribly convenient. Fortunately, Ruby comes packaged with
several alternatives. Of these, two of the best, class Mutex
and
class ConditionVariable
, are available in the thread
library
module; see the documentation beginning on page 457.
Mutex
is a class that implements a simple
semaphore lock for mutually exclusive access to some shared resource.
That is, only one thread may hold the lock at a given time. Other
threads may choose to wait in line for the lock to become available,
or may simply choose to get an immediate error indicating that the
lock is not available.
A mutex is often used when updates to shared data need to be atomic.
Say we need to update two variables as part of a transaction. We can
simulate this in a trivial program by incrementing some counters. The
updates are supposed to be atomic---the outside world should never see
the counters with different values. Without any kind of mutex control,
this just doesn't work.
count1 = count2 = 0
|
||
difference = 0
|
||
counter = Thread.new do
|
||
loop do
|
||
count1 += 1
|
||
count2 += 1
|
||
end
|
||
end
|
||
spy = Thread.new do
|
||
loop do
|
||
difference += (count1 - count2).abs
|
||
end
|
||
end
|
||
sleep 1
|
||
Thread.critical = 1
|
||
count1
|
» |
184846
|
count2
|
» |
184846
|
difference
|
» |
58126
|
count1
and count2
inconsistent.
Fortunately we can fix this using a mutex.
require 'thread' mutex = Mutex.new count1 = count2 = 0 difference = 0 counter = Thread.new do loop do mutex.synchronize do count1 += 1 count2 += 1 end end end spy = Thread.new do loop do mutex.synchronize do difference += (count1 - count2).abs end end end |
sleep 1
|
||
mutex.lock
|
||
count1
|
» |
21192
|
count2
|
» |
21192
|
difference
|
» |
0
|
require 'thread' mutex = Mutex.new cv = ConditionVariable.new a = Thread.new { mutex.synchronize { puts "A: I have critical section, but will wait for cv" cv.wait(mutex) puts "A: I have critical section again! I rule!" } } puts "(Later, back at the ranch...)" b = Thread.new { mutex.synchronize { puts "B: Now I am critical, but am done with cv" cv.signal puts "B: I am still critical, finishing up" } } a.join b.join |
A: I have critical section, but will wait for cv(Later, back at the ranch...) B: Now I am critical, but am done with cv B: I am still critical, finishing up A: I have critical section again! I rule! |
monitor.rb
and sync.rb
in the lib
subdirectory of the
distribution.
system
and backquote
methods.
system("tar xzf test.tgz")
|
» |
tar: test.tgz: Cannot open: No such file or directory\ntar: Error is not recoverable: exiting now\ntar: Child returned status 2\ntar: Error exit delayed from previous errors\nfalse
|
result = `date`
|
||
result
|
» |
"Sun Jun 9 00:08:50 CDT 2002\n"
|
Kernel::system
executes the given command in a
subprocess; it returns true
if the command was
found and executed properly, false
otherwise. In case of
failure, you'll find the subprocess's exit code in the global variable
$?
.
One problem with system
is that the command's output will
simply go to the same destination as your program's output, which may
not be what you want. To capture the standard output of a
subprocess, you can use the backquotes, as with `date`
in
the previous example. Remember that you may need to use
String#chomp
to remove the line-ending characters from the
result.
Okay, this is fine for simple cases---we can run some other process
and get the return status. But many times we need a bit more control
than that. We'd like to carry on a conversation with the subprocess,
possibly sending it data and possibly getting some back.
The method
IO.popen
does just this. The popen
method
runs a command as a subprocess and connects that subprocess's
standard input and standard output to a Ruby IO
object. Write to
the IO
object, and the subprocess can read it on standard
input. Whatever the subprocess writes is available in the Ruby program
by reading from the IO
object.
For example, on our systems one of the more useful utilities is
pig
, a program that reads words from standard input and prints
them in pig Latin (or igpay atinlay). We can use this when our Ruby
programs need to send us output that our 5-year-olds shouldn't be able to
understand.
pig = IO.popen("pig", "w+") pig.puts "ice cream after they go to bed" pig.close_write puts pig.gets |
iceway eamcray afterway eythay ogay otay edbay |
pig
program doesn't
flush the output it writes. Our original attempt at this example,
which had a pig.puts
followed by a pig.gets
, hung forever.
The pig
program processed our input, but its response was never
written to the pipe. We had to insert the pig.close_write
line.
This sends an end-of-file to pig
's standard input, and the output
we're looking for gets flushed as pig
terminates.
There's one more twist to popen
. If the command you pass it
is a single minus sign (``--''), popen
will fork a new Ruby
interpreter.
Both this and the original interpreter will continue
running by returning from the popen
. The original process
will receive an IO
object back, while the child will receive nil
.
pipe = IO.popen("-","w+") if pipe pipe.puts "Get a job!" $stderr.puts "Child says '#{pipe.gets.chomp}'" else $stderr.puts "Dad says '#{gets.chomp}'" puts "OK" end |
Dad says 'Get a job!' Child says 'OK' |
popen
, the traditional Unix calls
Kernel::fork
,
Kernel::exec
, and
IO.pipe
are
available on platforms that support them. The file-naming convention
of many IO
methods and
Kernel::open
will also spawn
subprocesses if you put a ``|
''
as the first character of the
filename (see the introduction to class IO
on page 325 for
details). Note that you cannot create pipes using
File.new
; it's just for files.
exec("sort testfile > output.txt") if fork == nil # The sort is now running in a child process # carry on processing in the main program # then wait for the sort to finish Process.wait |
Kernel::fork
returns a process id in the parent, and
nil
in the child, so the child process will perform the
Kernel::exec
call and run sort. Sometime later, we issue a
Process::wait
call, which waits for the sort to complete (and
returns its process id).
If you'd rather be notified when a child exits (instead of just
waiting around), you can set up a signal handler using
Kernel::trap
(described on page 427). Here we set
up a trap on SIGCLD
, which is the signal sent on ``death of child
process.''
trap("CLD") { pid = Process.wait puts "Child pid #{pid}: terminated" exit } exec("sort testfile > output.txt") if fork == nil # do other stuff... |
Child pid 31842: terminated |
IO.popen
works with a block in pretty much the same way as
File.open
does.
Pass popen
a command, such as date
, and the
block will be passed an IO
object as a parameter.
IO.popen ("date") { |f| puts "Date is #{f.gets}" } |
Date is Sun Jun 9 00:08:50 CDT 2002 |
IO
object will be closed automatically when the code block
exits, just as it is with
File.open
.
If you associate a block with
Kernel::fork
, the code in the
block will be run in a Ruby subprocess, and the parent will continue
after the block.
fork do puts "In child, pid = #$$" exit 99 end pid = Process.wait puts "Child terminated, pid = #{pid}, exit code = #{$? >> 8}" |
In child, pid = 31849 Child terminated, pid = 31849, exit code = 99 |
$?
8 bits to
the right before displaying it? This is a ``feature'' of Posix
systems: the bottom 8 bits of an exit code contain the reason the
program terminated, while the higher-order 8 bits hold the actual
exit
code.
Previous < |
Contents ^
|
Next >
|