ViewVC Help
View File | Revision Log | Show Annotations | Download File
/cvs/Guard/Guard.pm
Revision: 1.22
Committed: Sun Jul 26 08:07:11 2009 UTC (14 years, 9 months ago) by root
Branch: MAIN
Changes since 1.21: +24 -28 lines
Log Message:
*** empty log message ***

File Contents

# Content
1 =head1 NAME
2
3 Guard - safe cleanup blocks
4
5 =head1 SYNOPSIS
6
7 use Guard;
8
9 # temporarily chdir to "/etc" directory, but make sure
10 # to go back to "/" no matter how myfun exits:
11 sub myfun {
12 scope_guard { chdir "/" };
13 chdir "/etc";
14
15 code_that_might_die_or_does_other_fun_stuff;
16 }
17
18 # create an object that, when the last reference to it is gone,
19 # invokes the given codeblock:
20 my $guard = guard { print "destroyed!\n" };
21 undef $guard; # probably destroyed here
22
23 =head1 DESCRIPTION
24
25 This module implements so-called "guards". A guard is something (usually
26 an object) that "guards" a resource, ensuring that it is cleaned up when
27 expected.
28
29 Specifically, this module supports two different types of guards: guard
30 objects, which execute a given code block when destroyed, and scoped
31 guards, which are tied to the scope exit.
32
33 =head1 FUNCTIONS
34
35 This module currently exports the C<scope_guard> and C<guard> functions by
36 default.
37
38 =over 4
39
40 =cut
41
42 package Guard;
43
44 no warnings;
45
46 BEGIN {
47 $VERSION = '1.021';
48 @ISA = qw(Exporter);
49 @EXPORT = qw(guard scope_guard);
50
51 require Exporter;
52
53 require XSLoader;
54 XSLoader::load Guard, $VERSION;
55 }
56
57 our $DIED = sub { warn "$@" };
58
59 =item scope_guard BLOCK
60
61 Registers a block that is executed when the current scope (block,
62 function, method, eval etc.) is exited.
63
64 See the EXCEPTIONS section for an explanation of how exceptions
65 (i.e. C<die>) are handled inside guard blocks.
66
67 The description below sounds a bit complicated, but that's just because
68 C<scope_guard> tries to get even corner cases "right": the goal is to
69 provide you with a rock solid clean up tool.
70
71 The behaviour is similar to this code fragment:
72
73 eval ... code following scope_guard ...
74 {
75 local $@;
76 eval BLOCK;
77 eval { $Guard::DIED->() } if $@;
78 }
79 die if $@;
80
81 Except it is much faster, and the whole thing gets executed even when the
82 BLOCK calls C<exit>, C<goto>, C<last> or escapes via other means.
83
84 If multiple BLOCKs are registered to the same scope, they will be executed
85 in reverse order. Other scope-related things such as C<local> are managed
86 via the same mechanism, so variables C<local>ised I<after> calling
87 C<scope_guard> will be restored when the guard runs.
88
89 Example: temporarily change the timezone for the current process,
90 ensuring it will be reset when the C<if> scope is exited:
91
92 use Guard;
93 use POSIX ();
94
95 if ($need_to_switch_tz) {
96 # make sure we call tzset after $ENV{TZ} has been restored
97 scope_guard { POSIX::tzset };
98
99 # localise after the scope_guard, so it gets undone in time
100 local $ENV{TZ} = "Europe/London";
101 POSIX::tzset;
102
103 # do something with the new timezone
104 }
105
106 =item my $guard = guard BLOCK
107
108 Behaves the same as C<scope_guard>, except that instead of executing
109 the block on scope exit, it returns an object whose lifetime determines
110 when the BLOCK gets executed: when the last reference to the object gets
111 destroyed, the BLOCK gets executed as with C<scope_guard>.
112
113 See the EXCEPTIONS section for an explanation of how exceptions
114 (i.e. C<die>) are handled inside guard blocks.
115
116 Example: acquire a Coro::Semaphore for a second by registering a
117 timer. The timer callback references the guard used to unlock it
118 again. (Please ignore the fact that C<Coro::Semaphore> has a C<guard>
119 method that does this already):
120
121 use Guard;
122 use Coro::AnyEvent;
123 use Coro::Semaphore;
124
125 my $sem = new Coro::Semaphore;
126
127 sub lock_for_a_second {
128 $sem->down;
129 my $guard = guard { $sem->up };
130
131 Coro::AnyEvent::sleep 1;
132
133 # $sem->up gets executed when returning
134 }
135
136 The advantage of doing this with a guard instead of simply calling C<<
137 $sem->down >> in the callback is that you can opt not to create the timer,
138 or your code can throw an exception before it can create the timer (or
139 the thread gets canceled), or you can create multiple timers or other
140 event watchers and only when the last one gets executed will the lock be
141 unlocked. Using the C<guard>, you do not have to worry about catching all
142 the places where you have to unlock the semaphore.
143
144 =item $guard->cancel
145
146 Calling this function will "disable" the guard object returned by the
147 C<guard> function, i.e. it will free the BLOCK originally passed to
148 C<guard >and will arrange for the BLOCK not to be executed.
149
150 This can be useful when you use C<guard> to create a cleanup handler to be
151 called under fatal conditions and later decide it is no longer needed.
152
153 =cut
154
155 1;
156
157 =back
158
159 =head1 EXCEPTIONS
160
161 Guard blocks should not normally throw exceptions (that is, C<die>). After
162 all, they are usually used to clean up after such exceptions. However,
163 if something truly exceptional is happening, a guard block should of
164 course be allowed to die. Also, programming errors are a large source of
165 exceptions, and the programmer certainly wants to know about those.
166
167 Since in most cases, the block executing when the guard gets executed does
168 not know or does not care about the guard blocks, it makes little sense to
169 let containing code handle the exception.
170
171 Therefore, whenever a guard block throws an exception, it will be caught
172 by Guard, followed by calling the code reference stored in C<$Guard::DIED>
173 (with C<$@> set to the actual exception), which is similar to how most
174 event loops handle this case.
175
176 The default for C<$Guard::DIED> is to call C<warn "$@">, i.e. the error is
177 printed as a warning and the program continues.
178
179 The C<$@> variable will be restored to its value before the guard call in
180 all cases, so guards will not disturb C<$@> in any way.
181
182 The code reference stored in C<$Guard::DIED> should not die (behaviour is
183 not guaranteed, but right now, the exception will simply be ignored).
184
185 =head1 AUTHOR
186
187 Marc Lehmann <schmorp@schmorp.de>
188 http://home.schmorp.de/
189
190 =head1 THANKS
191
192 Thanks to Marco Maisenhelder, who reminded me of the C<$Guard::DIED>
193 solution to the problem of exceptions.
194
195 =head1 SEE ALSO
196
197 L<Scope::Guard> and L<Sub::ScopeFinalizer>, which actually implement
198 dynamic guards only, not scoped guards, and have a lot higher CPU, memory
199 and typing overhead.
200
201 L<Hook::Scope>, which has apparently never been finished and can corrupt
202 memory when used.
203
204 =cut
205