What, again?
Posted May 3, 2007 6:34 UTC (Thu) by
flewellyn (subscriber, #5047)
In reply to:
What, again? by ncm
Parent article:
The Rise of Functional Languages (Linux Journal)
To be very precise, if you put a socket in some larger data structure, you must explicitly
call
some cleanup function to ensure it gets closed in a timely fashion. You cannot automate this
management. You cannot write a library which invisibly embeds a socket without exposing to
the user a need to call your own cleanup function.
AHEM. I must be imagining the existence of the WITH-OPEN-FILE macro in the Common
Lisp
standard, which does exactly this: automates the closing of a file, invisibly, such that the user
need not be concerned with explicitly calling the CLOSE function. Within the macro body, the file
is referenced by the variable you give the macro as an argument; once control leaves the body of
the macro, you are guaranteed that the file has been closed. Even if code contained in the body
signals an error, the file WILL close.
Under the hood, of course, the macro expands into an UNWIND-PROTECT special form, in
which
the code that calls the necessary OPEN function and your code to work with the file are wrapped,
along with the cleanup code that CLOSEs the file, which UNWIND-PROTECT guarantees will run
when the form exits, normally or otherwise.
You'll see this idiom all over the place in Common Lisp libraries of all types. For instance,
sockets are not part
of the standard, since it was written before Berkeley Sockets became The One True Networking
Way, but every socket library I've seen for CL has a WITH-OPEN-SOCKET macro that handles
things the same way. Anywhere you have a resource that needs to be handled in a body of code
and then disposed of, the rule is the same: write a WITH-style macro that wraps the opening and
closing code in UNWIND-PROTECT, and then call the macro intead of worrying about the explicit
managment.
So you see, you CAN abstract management of non-memory resources, such that they are
always
correctly cleaned up. You just need proper macro support and something akin to UNWIND-
PROTECT.
(
Log in to post comments)