ViewVC Help
View File | Revision Log | Show Annotations | Download File
/cvs/Coro/Coro.pm
(Generate patch)

Comparing Coro/Coro.pm (file contents):
Revision 1.287 by root, Sat Feb 19 06:51:22 2011 UTC vs.
Revision 1.296 by root, Thu May 12 23:24:28 2011 UTC

196 196
197 async { 197 async {
198 Coro::terminate "return value 1", "return value 2"; 198 Coro::terminate "return value 1", "return value 2";
199 }; 199 };
200 200
201And yet another way is to C<< ->cancel >> the coro thread from another 201And yet another way is to C<< ->cancel >> (or C<< ->safe_cancel >>) the
202thread: 202coro thread from another thread:
203 203
204 my $coro = async { 204 my $coro = async {
205 exit 1; 205 exit 1;
206 }; 206 };
207 207
208 $coro->cancel; # an also accept values for ->join to retrieve 208 $coro->cancel; # also accepts values for ->join to retrieve
209 209
210Cancellation I<can> be dangerous - it's a bit like calling C<exit> without 210Cancellation I<can> be dangerous - it's a bit like calling C<exit> without
211actually exiting, and might leave C libraries and XS modules in a weird 211actually exiting, and might leave C libraries and XS modules in a weird
212state. Unlike other thread implementations, however, Coro is exceptionally 212state. Unlike other thread implementations, however, Coro is exceptionally
213safe with regards to cancellation, as perl will always be in a consistent 213safe with regards to cancellation, as perl will always be in a consistent
214state. 214state, and for those cases where you want to do truly marvellous things
215with your coro while it is being cancelled - that is, make sure all
216cleanup code is executed from the thread being cancelled - there is even a
217C<< ->safe_cancel >> method.
215 218
216So, cancelling a thread that runs in an XS event loop might not be the 219So, cancelling a thread that runs in an XS event loop might not be the
217best idea, but any other combination that deals with perl only (cancelling 220best idea, but any other combination that deals with perl only (cancelling
218when a thread is in a C<tie> method or an C<AUTOLOAD> for example) is 221when a thread is in a C<tie> method or an C<AUTOLOAD> for example) is
219safe. 222safe.
328 331
329our $idle; # idle handler 332our $idle; # idle handler
330our $main; # main coro 333our $main; # main coro
331our $current; # current coro 334our $current; # current coro
332 335
333our $VERSION = 5.37; 336our $VERSION = 5.372;
334 337
335our @EXPORT = qw(async async_pool cede schedule terminate current unblock_sub rouse_cb rouse_wait); 338our @EXPORT = qw(async async_pool cede schedule terminate current unblock_sub rouse_cb rouse_wait);
336our %EXPORT_TAGS = ( 339our %EXPORT_TAGS = (
337 prio => [qw(PRIO_MAX PRIO_HIGH PRIO_NORMAL PRIO_LOW PRIO_IDLE PRIO_MIN)], 340 prio => [qw(PRIO_MAX PRIO_HIGH PRIO_NORMAL PRIO_LOW PRIO_IDLE PRIO_MIN)],
338); 341);
399our @destroy; 402our @destroy;
400our $manager; 403our $manager;
401 404
402$manager = new Coro sub { 405$manager = new Coro sub {
403 while () { 406 while () {
404 Coro::State::cancel shift @destroy 407 _destroy shift @destroy
405 while @destroy; 408 while @destroy;
406 409
407 &schedule; 410 &schedule;
408 } 411 }
409}; 412};
543coro, regardless of priority. This is useful sometimes to ensure 546coro, regardless of priority. This is useful sometimes to ensure
544progress is made. 547progress is made.
545 548
546=item terminate [arg...] 549=item terminate [arg...]
547 550
548Terminates the current coro with the given status values (see L<cancel>). 551Terminates the current coro with the given status values (see
552L<cancel>). The values will not be copied, but referenced directly.
549 553
550=item Coro::on_enter BLOCK, Coro::on_leave BLOCK 554=item Coro::on_enter BLOCK, Coro::on_leave BLOCK
551 555
552These function install enter and leave winders in the current scope. The 556These function install enter and leave winders in the current scope. The
553enter block will be executed when on_enter is called and whenever the 557enter block will be executed when on_enter is called and whenever the
727Returns true iff this Coro object has been suspended. Suspended Coros will 731Returns true iff this Coro object has been suspended. Suspended Coros will
728not ever be scheduled. 732not ever be scheduled.
729 733
730=item $coro->cancel (arg...) 734=item $coro->cancel (arg...)
731 735
732Terminates the given Coro and makes it return the given arguments as 736Terminates the given Coro thread and makes it return the given arguments as
733status (default: the empty list). Never returns if the Coro is the 737status (default: an empty list). Never returns if the Coro is the
734current Coro. 738current Coro.
735 739
736=cut 740This is a rather brutal way to free a coro, with some limitations - if
741the thread is inside a C callback that doesn't expect to be canceled,
742bad things can happen, or if the cancelled thread insists on running
743complicated cleanup handlers that rely on it'S thread context, things will
744not work.
737 745
738sub cancel { 746Any cleanup code being run (e.g. from C<guard> blocks) will be run without
739 my $self = shift; 747a thread context, and is not allowed to switch to other threads. On the
748plus side, C<< ->cancel >> will always clean up the thread, no matter
749what. If your cleanup code is complex or you want to avoid cancelling a
750C-thread that doesn't know how to clean up itself, it can be better to C<<
751->throw >> an exception, or use C<< ->safe_cancel >>.
740 752
741 if ($current == $self) { 753The arguments to C<< ->cancel >> are not copied, but instead will
742 terminate @_; 754be referenced directly (e.g. if you pass C<$var> and after the call
743 } else { 755change that variable, then you might change the return values passed to
744 $self->{_status} = [@_]; 756e.g. C<join>, so don't do that).
745 Coro::State::cancel $self; 757
758The resources of the Coro are usually freed (or destructed) before this
759call returns, but this can be delayed for an indefinite amount of time, as
760in some cases the manager thread has to run first to actually destruct the
761Coro object.
762
763=item $coro->safe_cancel ($arg...)
764
765Works mostly like C<< ->cancel >>, but is inherently "safer", and
766consequently, can fail with an exception in cases the thread is not in a
767cancellable state.
768
769This method works a bit like throwing an exception that cannot be caught
770- specifically, it will clean up the thread from within itself, so
771all cleanup handlers (e.g. C<guard> blocks) are run with full thread
772context and can block if they wish. The downside is that there is no
773guarantee that the thread can be cancelled when you call this method, and
774therefore, it might fail. It is also considerably slower than C<cancel> or
775C<terminate>.
776
777A thread is in a safe-cancellable state if it either hasn't been run yet,
778or it has no C context attached and is inside an SLF function.
779
780The latter two basically mean that the thread isn't currently inside a
781perl callback called from some C function (usually via some XS modules)
782and isn't currently executing inside some C function itself (via Coro's XS
783API).
784
785This call returns true when it could cancel the thread, or croaks with an
786error otherwise (i.e. it either returns true or doesn't return at all).
787
788Why the weird interface? Well, there are two common models on how and
789when to cancel things. In the first, you have the expectation that your
790coro thread can be cancelled when you want to cancel it - if the thread
791isn't cancellable, this would be a bug somewhere, so C<< ->safe_cancel >>
792croaks to notify of the bug.
793
794In the second model you sometimes want to ask nicely to cancel a thread,
795but if it's not a good time, well, then don't cancel. This can be done
796relatively easy like this:
797
798 if (! eval { $coro->safe_cancel }) {
799 warn "unable to cancel thread: $@";
746 } 800 }
747} 801
802However, what you never should do is first try to cancel "safely" and
803if that fails, cancel the "hard" way with C<< ->cancel >>. That makes
804no sense: either you rely on being able to execute cleanup code in your
805thread context, or you don't. If you do, then C<< ->safe_cancel >> is the
806only way, and if you don't, then C<< ->cancel >> is always faster and more
807direct.
748 808
749=item $coro->schedule_to 809=item $coro->schedule_to
750 810
751Puts the current coro to sleep (like C<Coro::schedule>), but instead 811Puts the current coro to sleep (like C<Coro::schedule>), but instead
752of continuing with the next coro from the ready queue, always switch to 812of continuing with the next coro from the ready queue, always switch to
771inside the coro at the next convenient point in time. Otherwise 831inside the coro at the next convenient point in time. Otherwise
772clears the exception object. 832clears the exception object.
773 833
774Coro will check for the exception each time a schedule-like-function 834Coro will check for the exception each time a schedule-like-function
775returns, i.e. after each C<schedule>, C<cede>, C<< Coro::Semaphore->down 835returns, i.e. after each C<schedule>, C<cede>, C<< Coro::Semaphore->down
776>>, C<< Coro::Handle->readable >> and so on. Most of these functions 836>>, C<< Coro::Handle->readable >> and so on. Most of those functions (all
777detect this case and return early in case an exception is pending. 837that are part of Coro itself) detect this case and return early in case an
838exception is pending.
778 839
779The exception object will be thrown "as is" with the specified scalar in 840The exception object will be thrown "as is" with the specified scalar in
780C<$@>, i.e. if it is a string, no line number or newline will be appended 841C<$@>, i.e. if it is a string, no line number or newline will be appended
781(unlike with C<die>). 842(unlike with C<die>).
782 843
783This can be used as a softer means than C<cancel> to ask a coro to 844This can be used as a softer means than either C<cancel> or C<safe_cancel
784end itself, although there is no guarantee that the exception will lead to 845>to ask a coro to end itself, although there is no guarantee that the
785termination, and if the exception isn't caught it might well end the whole 846exception will lead to termination, and if the exception isn't caught it
786program. 847might well end the whole program.
787 848
788You might also think of C<throw> as being the moral equivalent of 849You might also think of C<throw> as being the moral equivalent of
789C<kill>ing a coro with a signal (in this case, a scalar). 850C<kill>ing a coro with a signal (in this case, a scalar).
790 851
791=item $coro->join 852=item $coro->join
792 853
793Wait until the coro terminates and return any values given to the 854Wait until the coro terminates and return any values given to the
794C<terminate> or C<cancel> functions. C<join> can be called concurrently 855C<terminate> or C<cancel> functions. C<join> can be called concurrently
795from multiple coro, and all will be resumed and given the status 856from multiple threads, and all will be resumed and given the status
796return once the C<$coro> terminates. 857return once the C<$coro> terminates.
797 858
798=cut 859=cut
799 860
800sub join { 861sub xjoin {
801 my $self = shift; 862 my $self = shift;
802 863
803 unless ($self->{_status}) { 864 unless ($self->{_status}) {
804 my $current = $current; 865 my $current = $current;
805 866
809 }; 870 };
810 871
811 &schedule while $current; 872 &schedule while $current;
812 } 873 }
813 874
814 wantarray ? @{$self->{_status}} : $self->{_status}[0]; 875 wantarray ? @{$self->{_status}} : $self->{_status}[0]
815} 876}
816 877
817=item $coro->on_destroy (\&cb) 878=item $coro->on_destroy (\&cb)
818 879
819Registers a callback that is called when this coro thread gets destroyed, 880Registers a callback that is called when this coro thread gets destroyed,
820but before it is joined. The callback gets passed the terminate arguments, 881that is, after it's resources have been freed but before it is joined. The
882callback gets passed the terminate/cancel arguments, if any, and I<must
821if any, and I<must not> die, under any circumstances. 883not> die, under any circumstances.
822 884
823There can be any number of C<on_destroy> callbacks per coro. 885There can be any number of C<on_destroy> callbacks per coro, and there is
886no way currently to remove a callback once added.
824 887
825=cut 888=cut
826 889
827sub on_destroy { 890sub xon_destroy {
828 my ($self, $cb) = @_; 891 my ($self, $cb) = @_;
829 892
830 push @{ $self->{_on_destroy} }, $cb; 893 push @{ $self->{_on_destroy} }, $cb;
831} 894}
832 895
1108future to allow per-thread schedulers, but Coro::State does not yet allow 1171future to allow per-thread schedulers, but Coro::State does not yet allow
1109this). I recommend disabling thread support and using processes, as having 1172this). I recommend disabling thread support and using processes, as having
1110the windows process emulation enabled under unix roughly halves perl 1173the windows process emulation enabled under unix roughly halves perl
1111performance, even when not used. 1174performance, even when not used.
1112 1175
1176Attempts to use threads created in another emulated process will crash
1177("cleanly", with a null pointer exception).
1178
1113=item coro switching is not signal safe 1179=item coro switching is not signal safe
1114 1180
1115You must not switch to another coro from within a signal handler (only 1181You must not switch to another coro from within a signal handler (only
1116relevant with %SIG - most event libraries provide safe signals), I<unless> 1182relevant with %SIG - most event libraries provide safe signals), I<unless>
1117you are sure you are not interrupting a Coro function. 1183you are sure you are not interrupting a Coro function.

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines