--- AnyEvent-MP/MP.pm 2009/08/03 22:05:55 1.20 +++ AnyEvent-MP/MP.pm 2009/08/04 14:10:51 1.21 @@ -30,7 +30,7 @@ on the same or other hosts. At the moment, this module family is severly brokena nd underdocumented, -so do not use. This was uploaded mainly to resreve the CPAN namespace - +so do not use. This was uploaded mainly to reserve the CPAN namespace - stay tuned! =head1 CONCEPTS @@ -86,9 +86,9 @@ our $VERSION = '0.02'; our @EXPORT = qw( - NODE $NODE $PORT snd rcv mon del _any_ + NODE $NODE $PORT snd rcv mon kil _any_ create_port create_port_on - create_miniport + miniport become_slave become_public ); @@ -122,6 +122,10 @@ =item $guard = mon $portid, $cb->() +=item $guard = mon $portid, $otherport + +=item $guard = mon $portid, $otherport, @msg + Monitor the given port and call the given callback when the port is destroyed or connection to it's node is lost. @@ -130,11 +134,22 @@ =cut sub mon { - my ($noderef, $port) = split /#/, shift, 2; + my ($noderef, $port, $cb) = ((split /#/, shift, 2), shift); my $node = AnyEvent::MP::Base::add_node $noderef; - my $cb = shift; + #TODO: ports must not be references + if (!ref $cb or "AnyEvent::MP::Port" eq ref $cb) { + if (@_) { + # send a kill info message + my (@msg) = ($cb, @_); + $cb = sub { snd @msg, @_ }; + } else { + # simply kill other port + my $port = $cb; + $cb = sub { kil $port, @_ }; + } + } $node->monitor ($port, $cb); @@ -142,6 +157,30 @@ and AnyEvent::Util::guard { $node->unmonitor ($port, $cb) } } +=item $guard = mon_guard $port, $ref, $ref... + +Monitors the given C<$port> and keeps the passed references. When the port +is killed, the references will be freed. + +Optionally returns a guard that will stop the monitoring. + +This function is useful when you create e.g. timers or other watchers and +want to free them when the port gets killed: + + $port->rcv (start => sub { + my $timer; $timer = mon_guard $port, AE::timer 1, 1, sub { + undef $timer if 0.9 < rand; + }); + }); + +=cut + +sub mon_guard { + my ($port, @refs) = @_; + + mon $port, sub { 0 && @refs } +} + =item $local_port = create_port Create a new local port object. See the next section for allowed methods. @@ -153,7 +192,6 @@ my $self = bless { id => "$NODE#$id", - names => [$id], }, "AnyEvent::MP::Port"; $AnyEvent::MP::Base::PORT{$id} = sub { @@ -206,7 +244,7 @@ $AnyEvent::MP::Base::PORT{$id} = sub { &$cb - and del $id; + and kil $id; }; "$NODE#$id" @@ -293,7 +331,7 @@ Explicitly destroy/remove/nuke/vaporise the port. -Ports are normally kept alive by there mere existance alone, and need to +Ports are normally kept alive by their mere existance alone, and need to be destroyed explicitly. =cut @@ -301,12 +339,9 @@ sub destroy { my ($self) = @_; - AnyEvent::MP::Base::del $self->{id}; - delete $AnyEvent::MP::Base::WKP{ $self->{wkname} }; - delete $AnyEvent::MP::Base::PORT{$_} - for @{ $self->{names} }; + AnyEvent::MP::Base::kil $self->{id}; } =back