Eric Hodel
10/29/2004 9:18:00 PM
On Oct 29, 2004, at 12:33 PM, Ara.T.Howard@noaa.gov wrote:
> On Sat, 30 Oct 2004, Eric Hodel wrote:
>
>> On Oct 28, 2004, at 9:53 PM, Ara.T.Howard wrote:
>>
>>> i have a program i'd like to exit gracefully on certain signals. the
>>> code spawns many threads which are never joined. however, when
>>> signaled i want to finished and pending threads before exiting -
>>> something like
>>>
>>> if $signaled
>>> Thread::list.each do |t|
>>> next if Thread::current == t
>>> begin
>>> t.join
>>> rescue => e
>>> warn{ e }
>>> end
>>> end
>>> end
>>>
>>> i'm wondering:
>>>
>>> if i spawn threads and never join them - will Thread::list grow
>>> without bound?
>>>
>>> are there any issues with iterating Thread::list - since this list is
>>> obviously changing all the time in this code (new Threads started)
>>
>> Have you seen the ThreadGroup class? A thread can only live in one
>> ThreadGroup, so you can create a ThreadGroup for spawned threads, add
>> the spawned threads to that ThreadGroup, then walk the ThreadGroup's
>> list on shutdown. This way you don't have to worry about killing
>> Thread.current
>
> i did look at that - however i'm worried that having a reference to
> the thread
> will maintain a reference that will keep it from getting GC'd. see, i
> normally simply spawn the threads and forget about them - it's only for
> catching signals that i need to shut down any running threads. does
> the above
> sound accurate?
ThreadGroups allow you to do that:
$ ruby
t = Thread.new { sleep 4 }
tg = ThreadGroup.new
tg.add t
p tg.list
sleep 10
p tg.list
[#<Thread:0x1cb878 sleep>]
[]