Resource management (computing): Difference between revisions

Content deleted Content added
Libnoon (talk | contribs)
Stack management and heap management: Talking about stack and heap is too specific (think about Python's "with" statement); this concept is more general and applies to lexical scope versus explicit releasing of the resource
Libnoon (talk | contribs)
Basic techniques: Remove the "def work_with_file" lines which are not useful
Line 37:
The basic approach to resource management is to acquire a resource, do something with it, then release it, yielding code of the form (illustrated with opening a file in Python):
<syntaxhighlight lang=python>
deff work_with_file= open(filename: str):
...
f = open(filename)
f.close()
...
f.close()
</syntaxhighlight>
This is correct if the intervening <code>...</code> code does not contain an early exit (<code>return</code>), the language does not have exceptions, and <code>open</code> is guaranteed to succeed. However, it causes a resource leak if there is a return or exception, and causes an incorrect release of unacquired resource if <code>open</code> can fail.
Line 48 ⟶ 47:
The resource leak can be resolved in languages that support a <code>finally</code> construction (like Python) by placing the body in a <code>try</code> clause, and the release in a <code>finally</code> clause:
<syntaxhighlight lang=python>
deff work_with_file= open(filename: str):
try:
f = open(filename)
try:...
finally:
...
finally:f.close()
f.close()
</syntaxhighlight>
This ensures correct release even if there is a return within the body or an exception thrown. Further, note that the acquisition occurs ''before'' the <code>try</code> clause, ensuring that the <code>finally</code> clause is only executed if the <code>open</code> code succeeds (without throwing an exception), assuming that "no exception" means "success" (as is the case for <code>open</code> in Python). If resource acquisition can fail without throwing an exception, such as by returning a form of <code>null</code>, it must also be checked before release, such as:
<syntaxhighlight lang=python>
deff work_with_file= open(filename: str):
try:
f = open(filename)
try:...
finally:
...
finallyif f:
if f:.close()
f.close()
</syntaxhighlight>
While this ensures correct resource management, it fails to provide adjacency or encapsulation. In many languages there are mechanisms that provide encapsulation, such as the <code>with</code> statement in Python:
<syntaxhighlight lang=python>
defwith work_with_fileopen(filename: str) as f:
...
with open(filename) as f:
...
</syntaxhighlight>