File.open{} , huge files and gc

G

gabriele renzi

I just came across a diuscussion about C++ smart pointers and Python's
refcount GC.
So I fall in the doubt:

If I call File.open 'my_huge_file' { |fd|
...
}

How should I feel? :)
I mean: would fd be freed or have I to manually start the GC after the
block?
actually the question could be: when GC gets called ?
 
T

Tom Felker

I just came across a diuscussion about C++ smart pointers and Python's
refcount GC.
So I fall in the doubt:

If I call File.open 'my_huge_file' { |fd|
..
}

How should I feel? :)
I mean: would fd be freed or have I to manually start the GC after the
block?
actually the question could be: when GC gets called ?

The price you pay for not needing to keep track of the ownership and
deallocation of everything you allocate is that you can't be certain when
your object will be deleted. In other words, there's a constructor, but
no destructor.

You can force the GC to run, but this is kind of a hack. (I'm not sure if
you're guaranteed the GC will finish before GC.start returns.) Also,
there are destructors, but they're very hackish and are not encouraged.

In practice, in GC'd languages, objects need to manage their non-memory
resources (like open file descriptors) differently. In C++ the resources
are freed when the object is destroyed. In Ruby, it's typical to make a
function that allocates, yields, and frees.

So to answer your question, File.open works that way. When you pass it a
block, File.open closes the file descriptor after the block is finished.
The fd structure in memory still exists until the GC runs, but as far as
the operating system is concerned, the file is closed.
 
R

Robert Klemme

gabriele renzi said:
I just came across a diuscussion about C++ smart pointers and Python's
refcount GC.
So I fall in the doubt:

If I call File.open 'my_huge_file' { |fd|
..
}

How should I feel? :)
I mean: would fd be freed or have I to manually start the GC after the
block?

I don't see the problem since fd is just the File instance, i.e. mainly
the file handle. That doesn't consume much mem. It especially consumes
the same amount of mem for every file (at least it's likely to be bounded
by a buffer size.)

Or am I wrong?
actually the question could be: when GC gets called ?

Whenever ruby feels like it or you tell the interpreter. :)

robert
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,776
Messages
2,569,603
Members
45,189
Latest member
CryptoTaxSoftware

Latest Threads

Top