Without more concrete examples, this has to remain somewhat abstract:
With "real" global variables, you won't get memory leaks, as these variables are truely global and basically referred to by their name instead of a counted reference anyway. The great aspect of global variables is that they are accessible from everywhere, so you can clear them out or change them once it becomes necessary in your program. So using our is unproblematic in any case.
With "lexical global" variables (or "file scope lexical" variables), that is, variables declared using my but near the top of your file, these variables will be shared between all callback instances that use them. This can still lead to some memory leaking, but as these variables are, by almost all intents, global too, it's just a little bit worse than using a real global variable.
With lexical variables declared "just above" your callback and then used in your callback, things become complicated:
The first case is if your callback simply closes over a lexical variable, like in the below code. Then, $message will basically be only used by $callback and thus only stay alive as long as $callback stays alive.
sub handle_foo {
my $message= 'Example';
my $callback= sub {
print $message;
};
...
};
The problematic part comes when a subroutine closes over a variable that in turn holds a reference to the subroutine. This will basically prevent the reference counting garbage collection from reclaiming the memory for the variable, the closure and all variables that hang off the closure until the end of the process:
sub fetch_item {
my( $item, $on_success )= @_;
my $fetch; $fetch= sub {
http_get( $item,
success => $on_success,
error => sub {
if( can_retry( $item ) ) {
goto &$fetch;
};
},
};
};
In the above case, the callback subroutine stored in $fetch closes over $fetch itself and thus the closure created with each call to fetch_item will ever be automatically reclaimed until the end of the process. The pattern proposed in AnyEvent is to manually undefine $fetch at the end of every relevant callback:
sub fetch_item {
my( $item, $on_success )= @_;
my $fetch; $fetch= sub {
http_get( $item,
success => sub {
undef $fetch; # we are done
goto &$on_success;
};
error => sub {
if( can_retry( $item ) ) {
goto &$fetch;
} else {
undef $fetch; # we are done retrying
};
},
};
};
|