ViewVC Help
View File | Revision Log | Show Annotations | Download File
/cvs/Guard/Guard.pm
Revision: 1.20
Committed: Mon Jun 1 10:33:16 2009 UTC (14 years, 11 months ago) by root
Branch: MAIN
Changes since 1.19: +5 -0 lines
Log Message:
*** empty log message ***

File Contents

# User Rev Content
1 root 1.1 =head1 NAME
2    
3     Guard - safe cleanup blocks
4    
5     =head1 SYNOPSIS
6    
7 root 1.9 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 root 1.15 code_that_might_die_or_does_other_fun_stuff;
16 root 1.9 }
17 root 1.4
18 root 1.20 # 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 root 1.1 =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 root 1.2 =head1 FUNCTIONS
34    
35     This module currently exports the C<scope_guard> and C<guard> functions by
36     default.
37    
38 root 1.1 =over 4
39    
40     =cut
41    
42     package Guard;
43    
44 root 1.13 no warnings;
45    
46 root 1.1 BEGIN {
47 root 1.19 $VERSION = '1.02';
48 root 1.1 @ISA = qw(Exporter);
49 root 1.3 @EXPORT = qw(guard scope_guard);
50 root 1.1
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 root 1.8 See the EXCEPTIONS section for an explanation of how exceptions
65     (i.e. C<die>) are handled inside guard blocks.
66    
67 root 1.2 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 root 1.8 The behaviour is similar to this code fragment:
72 root 1.1
73     eval ... code following scope_guard ...
74     {
75     local $@;
76     eval BLOCK;
77     eval { $Guard::DIED->() } if $@;
78     }
79 root 1.2 die if $@;
80 root 1.1
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 root 1.4 If multiple BLOCKs are registered to the same scope, they will be executed
85 root 1.8 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 root 1.1
89 root 1.4 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 root 1.1
99 root 1.4 # localise after the scope_guard, so it gets undone in time
100     local $ENV{TZ} = "Europe/London";
101     POSIX::tzset;
102 root 1.1
103 root 1.4 # do something with the new timezone
104 root 1.1 }
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     The returned object can be copied as many times as you want.
114    
115 root 1.8 See the EXCEPTIONS section for an explanation of how exceptions
116     (i.e. C<die>) are handled inside guard blocks.
117 root 1.1
118     Example: acquire a Coro::Semaphore for a second by registering a
119 root 1.10 timer. The timer callback references the guard used to unlock it
120     again. (Please ignore the fact that C<Coro::Semaphore> has a C<guard>
121     method that does this already):
122 root 1.1
123 root 1.9 use Guard;
124 root 1.1 use AnyEvent;
125     use Coro::Semaphore;
126    
127     my $sem = new Coro::Semaphore;
128    
129 root 1.9 sub lock_for_a_second {
130 root 1.1 $sem->down;
131     my $guard = guard { $sem->up };
132    
133     my $timer;
134     $timer = AnyEvent->timer (after => 1, sub {
135     # do something
136     undef $sem;
137     undef $timer;
138     });
139     }
140    
141     The advantage of doing this with a guard instead of simply calling C<<
142     $sem->down >> in the callback is that you can opt not to create the timer,
143     or your code can throw an exception before it can create the timer, or you
144     can create multiple timers or other event watchers and only when the last
145 root 1.11 one gets executed will the lock be unlocked. Using the C<guard>, you do
146     not have to worry about catching all the places where you have to unlock
147     the semaphore.
148 root 1.1
149 root 1.13 =item $guard->cancel
150 root 1.1
151     Calling this function will "disable" the guard object returned by the
152     C<guard> function, i.e. it will free the BLOCK originally passed to
153     C<guard >and will arrange for the BLOCK not to be executed.
154    
155     This can be useful when you use C<guard> to create a fatal cleanup handler
156     and later decide it is no longer needed.
157    
158     =cut
159    
160     1;
161    
162     =back
163    
164     =head1 EXCEPTIONS
165    
166 root 1.5 Guard blocks should not normally throw exceptions (that is, C<die>). After
167 root 1.1 all, they are usually used to clean up after such exceptions. However, if
168     something truly exceptional is happening, a guard block should be allowed
169     to die. Also, programming errors are a large source of exceptions, and the
170     programmer certainly wants to know about those.
171    
172 root 1.14 Since in most cases, the block executing when the guard gets executed does
173 root 1.1 not know or does not care about the guard blocks, it makes little sense to
174     let containing code handle the exception.
175    
176     Therefore, whenever a guard block throws an exception, it will be caught,
177 root 1.14 followed by calling the code reference stored in C<$Guard::DIED> (with
178     C<$@> set to the actual exception), which is similar to how most event
179     loops handle this case.
180 root 1.1
181 root 1.12 The default for C<$Guard::DIED> is to call C<warn "$@">.
182    
183     The C<$@> variable will be restored to its value before the guard call in
184     all cases, so guards will not disturb C<$@> in any way.
185    
186 root 1.1 The code reference stored in C<$Guard::DIED> should not die (behaviour is
187     not guaranteed, but right now, the exception will simply be ignored).
188    
189     =head1 AUTHOR
190    
191     Marc Lehmann <schmorp@schmorp.de>
192     http://home.schmorp.de/
193    
194     =head1 THANKS
195    
196 root 1.6 Thanks to Marco Maisenhelder, who reminded me of the C<$Guard::DIED>
197     solution to the problem of exceptions.
198 root 1.1
199 root 1.16 =head1 SEE ALSO
200    
201     L<Scope::Guard> and L<Sub::ScopeFinalizer>, which actually implement
202     dynamic, not scoped guards, and have a lot higher CPU, memory and typing
203     overhead.
204    
205     L<Hook::Scope>, which has apparently never been finished and corrupts
206     memory when used.
207    
208 root 1.1 =cut
209