4 ms·
Seems like the problem is that file close is strict, whereas the file handle should be a locked resource that is auto-closed when the last reference is destroye
by garmaine 7y ago
Seems like the problem is that file close is strict, whereas the file handle should be a locked resource that is auto-closed when the last reference is destroyed (and “fclose” just releases the habdle’s own lock).
In other words the problem seems to be (in this example) that the standard library mixes lazy and strict semantics. A better library wouldn’t carry that flaw.
- dllthomas 7y agoSo that's actually how it works if you just ignore hClose. The problem is that it sometimes matters when things get closed, so they do "need" to expose the ability to close things sooner.
- garmaine 7y agoSort of. It eventually gets cleaned up by the garbage collector, yes. But that could be after an indeterministic amount of time if the GC is mark-and-sweep. My point is that in this circumstance reference counting could be used regardless so that as soon as the last thunk is read, the file is closed. The 'hClose' is basically making a promise to close the file as soon as it is safe to do so.
- dllthomas 7y ago> as soon as the last thunk is read, the file is closed. That's probably doable. It's true that when the only reference to the handle in question is the one buried in the thunk pointed at by the lazy input, it should be safe to close it when a thunk evaluates to end-of-input (or an error, for that matter). I'm not sure whether or not it'd be applicable enough to be worth doing. The immediate issues I spot are that a lot of input streams aren't consumed all the way to the end, and that you'd have to be careful not to capture a reference anywhere else (or you'll be waiting for GC to remove that reference before the count falls to zero).
- garmaine 7y agoAlso things like unix pipes or network sockets, where the "close" operation means something different as there are multiple parties involved. Arguably the same is true of files as you could be reading a file being simultaneously written to by others.
- dllthomas 7y agoRight. It's easy to handle the simple case, but honestly "let the GC close it" works fine in the simplest cases.