Tuesday, November 28, 2006

Pages 129-30: Manipulating threads, thread variables


Listen to this article.

Value: High

Level: Hard

Summary:
When a Ruby program terminates, all threads are killed, regardless of their states. Thread#join blocks the program until the calling thread is finished. Other useful methods are: Thread#value(), Thread.current, Thread.list, Thread#status and Thread#alive?, Thread#priority=(). If you need per-thread variables that can be accessed by other threads, including the main thread, you can treat the thread object as an Hash with two special methods, Thread#[]=() and Thread#[].

Memo: You can give Thread#join a timeout parameter. If your threads share a variable, beware of race conditions.

Example:

count = 0
threads = []
10.times do |i|
threads[i] = Thread.new do
Thread.current["mycount"] = count
count += 1
end
end
threads.each do |t|
t.join
print "#{t}'s count= #{t["mycount"]}\n"
end
puts "Final count = #{count}"

Reported errata (at 10/17/06 14:17:18 PDT): 0

Errata I found : 1

  • On page 129, second paragraph, you find this sentence: "The calling thread will block until the given thread is finished". As the verb "to block" is transitive, it seems to lack the object, to say "your program".

My suggestions to the author: 3 (4)

  • Make the first example code on page 130 more clear and comprehensible.
    • Pull out the 5th line.
    • Explode the block on the 10th line.
  • Give an example for Thread#value
  • Explain in detail how Thread#[]= and Thread#[] *exactly* work

Doubts: 1 (6)
  • How do Thread#[]= and Thread#[] *exactly* work ?
    • Do they automatically create an Hash object assigning it to a variable whose name is the same as the thread object id ?
    • What is the scope of this special Hash object ?
    • Does this special Hash object exist just to give you access to per-thread variables from other threads or does it have other uses, too ?
    • How many pairs of key and value can this special Hash object hold ?
    • Why can I retrieve the value associated with the/a key of this special Hash object treating the key either as a standard key or as a symbol, while this procedure is not allowed when dealing with a standard Hash object ?

0 Comments:

Post a Comment

<< Home