From: Nobuyoshi Nakada Date: 2011-12-23T02:26:29+09:00 Subject: [ruby-core:41785] [ruby-trunk - Feature #5788][Feedback] Thread#at_exit Issue #5788 has been updated by Nobuyoshi Nakada. Status changed from Open to Feedback =begin Just reviewed briefly. * (({th->at_exit})) needs to be marked, * (({th->at_exit})) should be hidden, and * a hook registered to the main thread seems to be executed in a child process forked in a sub-thread too. Second, what will happen if the thread has terminated already? Also, it might be useful if the thread or its value is passed to the hook. =end ---------------------------------------- Feature #5788: Thread#at_exit https://bugs.ruby-lang.org/issues/5788 Author: Masaki Matsushita Status: Feedback Priority: Normal Assignee: Category: core Target version: =begin I propose a new method Thread#at_exit. It is to register a block which will be called when the thread ends. p Thread.main #=> # p t = Thread.new{ # do something } #=> # t.at_exit{ p Thread.current } t.join #=> # Thread.main.at_exit is equal to Kernel.at_exit. I think this method is useful for waiting plural running threads end. Without Thread#at_exit: t1 = Thread.new{ sleep 1 } t2 = Thread.new{ sleep 2 } [t1, t2].each do |t| Thread.new do t.join puts "Thread ended!" end end [t1, t2].each(&:join) To handle threads' end immediately, the same number of threads as ones to wait is needed. For example, Ruby's standard library thwait.rb does so. With Thread#at_exit: t1 = Thread.new{ sleep 1 } t2 = Thread.new{ sleep 2 } [t1, t2].each do |t| # It runs when interpreter ends. t.at_exit{ puts "Thread ended!" } end New threads are not necessary. I made a patch. Patched ruby passes test-all. =end -- http://redmine.ruby-lang.org