Thursday, November 30, 2006

Fwd: Pages 130-1: Threads and Exceptions


Listen to this article.

Value: Medium

Level: Easy

Summary:
By default if a thread raises an unhandled exception, the exception kills the thread. If you set the abort_on_exception flag to true, or use -d to turn on the interpreter debug flag, an unhandled exception kills all running threads.

Memo: Inside threads, you better use print() instead of puts().

Example:

threads = []
4.times do |number|
    threads << Thread.new(number) do |i|
        raise "Boom!" if i == 2
        print "#{i}\n"
    end
end
threads.each {|t| t.join }

Thread.abort_on_exception = true
threads = []
4.times do |number|
    threads << Thread.new(number) do |i|
        raise "Boom!" if i == 2
        print "#{i}\n"
    end
end
threads.each {|t| t.join }

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

Errata I found: 0

My suggestions to the author: 1

  • In the last paragraph on page 121 the author explains why is not safe to use puts() inside threads. Unfortunately the explanation is not exhaustive, because the modal verbs in the statement "a thread could get scheduled, and the output would be interleaved" do not make clear the rule behind the phenomenon.

Doubts: 1

  • Is there a rule behind the fact that if I use puts() inside threads "a thread could get scheduled, and the output would be interleaved" ? 

0 Comments:

Post a Comment

<< Home