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

Comparing cvsroot/Coro/Coro.pm (file contents):
Revision 1.253 by root, Fri May 29 07:01:18 2009 UTC vs.
Revision 1.285 by root, Thu Feb 17 01:32:18 2011 UTC

40points in your program, so locking and parallel access are rarely an 40points in your program, so locking and parallel access are rarely an
41issue, making thread programming much safer and easier than using other 41issue, making thread programming much safer and easier than using other
42thread models. 42thread models.
43 43
44Unlike the so-called "Perl threads" (which are not actually real threads 44Unlike the so-called "Perl threads" (which are not actually real threads
45but only the windows process emulation ported to unix, and as such act 45but only the windows process emulation (see section of same name for more
46as processes), Coro provides a full shared address space, which makes 46details) ported to unix, and as such act as processes), Coro provides
47communication between threads very easy. And Coro's threads are fast, 47a full shared address space, which makes communication between threads
48too: disabling the Windows process emulation code in your perl and using 48very easy. And Coro's threads are fast, too: disabling the Windows
49Coro can easily result in a two to four times speed increase for your 49process emulation code in your perl and using Coro can easily result in
50programs. A parallel matrix multiplication benchmark runs over 300 times 50a two to four times speed increase for your programs. A parallel matrix
51faster on a single core than perl's pseudo-threads on a quad core using 51multiplication benchmark runs over 300 times faster on a single core than
52all four cores. 52perl's pseudo-threads on a quad core using all four cores.
53 53
54Coro achieves that by supporting multiple running interpreters that share 54Coro achieves that by supporting multiple running interpreters that share
55data, which is especially useful to code pseudo-parallel processes and 55data, which is especially useful to code pseudo-parallel processes and
56for event-based programming, such as multiple HTTP-GET requests running 56for event-based programming, such as multiple HTTP-GET requests running
57concurrently. See L<Coro::AnyEvent> to learn more on how to integrate Coro 57concurrently. See L<Coro::AnyEvent> to learn more on how to integrate Coro
67 67
68=cut 68=cut
69 69
70package Coro; 70package Coro;
71 71
72use strict qw(vars subs); 72use common::sense;
73no warnings "uninitialized"; 73
74use Carp ();
74 75
75use Guard (); 76use Guard ();
76 77
77use Coro::State; 78use Coro::State;
78 79
80 81
81our $idle; # idle handler 82our $idle; # idle handler
82our $main; # main coro 83our $main; # main coro
83our $current; # current coro 84our $current; # current coro
84 85
85our $VERSION = 5.132; 86our $VERSION = 5.26;
86 87
87our @EXPORT = qw(async async_pool cede schedule terminate current unblock_sub); 88our @EXPORT = qw(async async_pool cede schedule terminate current unblock_sub rouse_cb rouse_wait);
88our %EXPORT_TAGS = ( 89our %EXPORT_TAGS = (
89 prio => [qw(PRIO_MAX PRIO_HIGH PRIO_NORMAL PRIO_LOW PRIO_IDLE PRIO_MIN)], 90 prio => [qw(PRIO_MAX PRIO_HIGH PRIO_NORMAL PRIO_LOW PRIO_IDLE PRIO_MIN)],
90); 91);
91our @EXPORT_OK = (@{$EXPORT_TAGS{prio}}, qw(nready)); 92our @EXPORT_OK = (@{$EXPORT_TAGS{prio}}, qw(nready));
92 93
123 124
124This variable is mainly useful to integrate Coro into event loops. It is 125This variable is mainly useful to integrate Coro into event loops. It is
125usually better to rely on L<Coro::AnyEvent> or L<Coro::EV>, as this is 126usually better to rely on L<Coro::AnyEvent> or L<Coro::EV>, as this is
126pretty low-level functionality. 127pretty low-level functionality.
127 128
128This variable stores either a Coro object or a callback. 129This variable stores a Coro object that is put into the ready queue when
130there are no other ready threads (without invoking any ready hooks).
129 131
130If it is a callback, the it is called whenever the scheduler finds no 132The default implementation dies with "FATAL: deadlock detected.", followed
131ready coros to run. The default implementation prints "FATAL: 133by a thread listing, because the program has no other way to continue.
132deadlock detected" and exits, because the program has no other way to
133continue.
134
135If it is a coro object, then this object will be readied (without
136invoking any ready hooks, however) when the scheduler finds no other ready
137coros to run.
138 134
139This hook is overwritten by modules such as C<Coro::EV> and 135This hook is overwritten by modules such as C<Coro::EV> and
140C<Coro::AnyEvent> to wait on an external event that hopefully wake up a 136C<Coro::AnyEvent> to wait on an external event that hopefully wakes up a
141coro so the scheduler can run it. 137coro so the scheduler can run it.
142 138
143Note that the callback I<must not>, under any circumstances, block
144the current coro. Normally, this is achieved by having an "idle
145coro" that calls the event loop and then blocks again, and then
146readying that coro in the idle handler, or by simply placing the idle
147coro in this variable.
148
149See L<Coro::Event> or L<Coro::AnyEvent> for examples of using this 139See L<Coro::EV> or L<Coro::AnyEvent> for examples of using this technique.
150technique.
151 140
152Please note that if your callback recursively invokes perl (e.g. for event
153handlers), then it must be prepared to be called recursively itself.
154
155=cut 141=cut
156 142
157$idle = sub { 143# ||= because other modules could have provided their own by now
158 require Carp; 144$idle ||= new Coro sub {
159 Carp::croak ("FATAL: deadlock detected"); 145 require Coro::Debug;
146 die "FATAL: deadlock detected.\n"
147 . Coro::Debug::ps_listing ();
160}; 148};
161 149
162# this coro is necessary because a coro 150# this coro is necessary because a coro
163# cannot destroy itself. 151# cannot destroy itself.
164our @destroy; 152our @destroy;
206Example: Create a new coro that just prints its arguments. 194Example: Create a new coro that just prints its arguments.
207 195
208 async { 196 async {
209 print "@_\n"; 197 print "@_\n";
210 } 1,2,3,4; 198 } 1,2,3,4;
211
212=cut
213
214sub async(&@) {
215 my $coro = new Coro @_;
216 $coro->ready;
217 $coro
218}
219 199
220=item async_pool { ... } [@args...] 200=item async_pool { ... } [@args...]
221 201
222Similar to C<async>, but uses a coro pool, so you should not call 202Similar to C<async>, but uses a coro pool, so you should not call
223terminate or join on it (although you are allowed to), and you get a 203terminate or join on it (although you are allowed to), and you get a
280=item schedule 260=item schedule
281 261
282Calls the scheduler. The scheduler will find the next coro that is 262Calls the scheduler. The scheduler will find the next coro that is
283to be run from the ready queue and switches to it. The next coro 263to be run from the ready queue and switches to it. The next coro
284to be run is simply the one with the highest priority that is longest 264to be run is simply the one with the highest priority that is longest
285in its ready queue. If there is no coro ready, it will clal the 265in its ready queue. If there is no coro ready, it will call the
286C<$Coro::idle> hook. 266C<$Coro::idle> hook.
287 267
288Please note that the current coro will I<not> be put into the ready 268Please note that the current coro will I<not> be put into the ready
289queue, so calling this function usually means you will never be called 269queue, so calling this function usually means you will never be called
290again unless something else (e.g. an event handler) calls C<< ->ready >>, 270again unless something else (e.g. an event handler) calls C<< ->ready >>,
338 318
339These functions implement the same concept as C<dynamic-wind> in scheme 319These functions implement the same concept as C<dynamic-wind> in scheme
340does, and are useful when you want to localise some resource to a specific 320does, and are useful when you want to localise some resource to a specific
341coro. 321coro.
342 322
343They slow down coro switching considerably for coros that use 323They slow down thread switching considerably for coros that use them
344them (But coro switching is still reasonably fast if the handlers are 324(about 40% for a BLOCK with a single assignment, so thread switching is
345fast). 325still reasonably fast if the handlers are fast).
346 326
347These functions are best understood by an example: The following function 327These functions are best understood by an example: The following function
348will change the current timezone to "Antarctica/South_Pole", which 328will change the current timezone to "Antarctica/South_Pole", which
349requires a call to C<tzset>, but by using C<on_enter> and C<on_leave>, 329requires a call to C<tzset>, but by using C<on_enter> and C<on_leave>,
350which remember/change the current timezone and restore the previous 330which remember/change the current timezone and restore the previous
373 }; 353 };
374 354
375This can be used to localise about any resource (locale, uid, current 355This can be used to localise about any resource (locale, uid, current
376working directory etc.) to a block, despite the existance of other 356working directory etc.) to a block, despite the existance of other
377coros. 357coros.
358
359Another interesting example implements time-sliced multitasking using
360interval timers (this could obviously be optimised, but does the job):
361
362 # "timeslice" the given block
363 sub timeslice(&) {
364 use Time::HiRes ();
365
366 Coro::on_enter {
367 # on entering the thread, we set an VTALRM handler to cede
368 $SIG{VTALRM} = sub { cede };
369 # and then start the interval timer
370 Time::HiRes::setitimer &Time::HiRes::ITIMER_VIRTUAL, 0.01, 0.01;
371 };
372 Coro::on_leave {
373 # on leaving the thread, we stop the interval timer again
374 Time::HiRes::setitimer &Time::HiRes::ITIMER_VIRTUAL, 0, 0;
375 };
376
377 &{+shift};
378 }
379
380 # use like this:
381 timeslice {
382 # The following is an endless loop that would normally
383 # monopolise the process. Since it runs in a timesliced
384 # environment, it will regularly cede to other threads.
385 while () { }
386 };
387
378 388
379=item killall 389=item killall
380 390
381Kills/terminates/cancels all coros except the currently running one. 391Kills/terminates/cancels all coros except the currently running one.
382 392
557 wantarray ? @{$self->{_status}} : $self->{_status}[0]; 567 wantarray ? @{$self->{_status}} : $self->{_status}[0];
558} 568}
559 569
560=item $coro->on_destroy (\&cb) 570=item $coro->on_destroy (\&cb)
561 571
562Registers a callback that is called when this coro gets destroyed, 572Registers a callback that is called when this coro thread gets destroyed,
563but before it is joined. The callback gets passed the terminate arguments, 573but before it is joined. The callback gets passed the terminate arguments,
564if any, and I<must not> die, under any circumstances. 574if any, and I<must not> die, under any circumstances.
565 575
576There can be any number of C<on_destroy> callbacks per coro.
577
566=cut 578=cut
567 579
568sub on_destroy { 580sub on_destroy {
569 my ($self, $cb) = @_; 581 my ($self, $cb) = @_;
570 582
572} 584}
573 585
574=item $oldprio = $coro->prio ($newprio) 586=item $oldprio = $coro->prio ($newprio)
575 587
576Sets (or gets, if the argument is missing) the priority of the 588Sets (or gets, if the argument is missing) the priority of the
577coro. Higher priority coro get run before lower priority 589coro thread. Higher priority coro get run before lower priority
578coro. Priorities are small signed integers (currently -4 .. +3), 590coros. Priorities are small signed integers (currently -4 .. +3),
579that you can refer to using PRIO_xxx constants (use the import tag :prio 591that you can refer to using PRIO_xxx constants (use the import tag :prio
580to get then): 592to get then):
581 593
582 PRIO_MAX > PRIO_HIGH > PRIO_NORMAL > PRIO_LOW > PRIO_IDLE > PRIO_MIN 594 PRIO_MAX > PRIO_HIGH > PRIO_NORMAL > PRIO_LOW > PRIO_IDLE > PRIO_MIN
583 3 > 1 > 0 > -1 > -3 > -4 595 3 > 1 > 0 > -1 > -3 > -4
584 596
585 # set priority to HIGH 597 # set priority to HIGH
586 current->prio (PRIO_HIGH); 598 current->prio (PRIO_HIGH);
587 599
588The idle coro ($Coro::idle) always has a lower priority than any 600The idle coro thread ($Coro::idle) always has a lower priority than any
589existing coro. 601existing coro.
590 602
591Changing the priority of the current coro will take effect immediately, 603Changing the priority of the current coro will take effect immediately,
592but changing the priority of coro in the ready queue (but not 604but changing the priority of a coro in the ready queue (but not running)
593running) will only take effect after the next schedule (of that 605will only take effect after the next schedule (of that coro). This is a
594coro). This is a bug that will be fixed in some future version. 606bug that will be fixed in some future version.
595 607
596=item $newprio = $coro->nice ($change) 608=item $newprio = $coro->nice ($change)
597 609
598Similar to C<prio>, but subtract the given value from the priority (i.e. 610Similar to C<prio>, but subtract the given value from the priority (i.e.
599higher values mean lower priority, just as in unix). 611higher values mean lower priority, just as in UNIX's nice command).
600 612
601=item $olddesc = $coro->desc ($newdesc) 613=item $olddesc = $coro->desc ($newdesc)
602 614
603Sets (or gets in case the argument is missing) the description for this 615Sets (or gets in case the argument is missing) the description for this
604coro. This is just a free-form string you can associate with a 616coro thread. This is just a free-form string you can associate with a
605coro. 617coro.
606 618
607This method simply sets the C<< $coro->{desc} >> member to the given 619This method simply sets the C<< $coro->{desc} >> member to the given
608string. You can modify this member directly if you wish. 620string. You can modify this member directly if you wish, and in fact, this
621is often preferred to indicate major processing states that cna then be
622seen for example in a L<Coro::Debug> session:
623
624 sub my_long_function {
625 local $Coro::current->{desc} = "now in my_long_function";
626 ...
627 $Coro::current->{desc} = "my_long_function: phase 1";
628 ...
629 $Coro::current->{desc} = "my_long_function: phase 2";
630 ...
631 }
609 632
610=cut 633=cut
611 634
612sub desc { 635sub desc {
613 my $old = $_[0]{desc}; 636 my $old = $_[0]{desc};
650returning a new coderef. Unblocking means that calling the new coderef 673returning a new coderef. Unblocking means that calling the new coderef
651will return immediately without blocking, returning nothing, while the 674will return immediately without blocking, returning nothing, while the
652original code ref will be called (with parameters) from within another 675original code ref will be called (with parameters) from within another
653coro. 676coro.
654 677
655The reason this function exists is that many event libraries (such as the 678The reason this function exists is that many event libraries (such as
656venerable L<Event|Event> module) are not thread-safe (a weaker form 679the venerable L<Event|Event> module) are not thread-safe (a weaker form
657of reentrancy). This means you must not block within event callbacks, 680of reentrancy). This means you must not block within event callbacks,
658otherwise you might suffer from crashes or worse. The only event library 681otherwise you might suffer from crashes or worse. The only event library
659currently known that is safe to use without C<unblock_sub> is L<EV>. 682currently known that is safe to use without C<unblock_sub> is L<EV> (but
683you might still run into deadlocks if all event loops are blocked).
684
685Coro will try to catch you when you block in the event loop
686("FATAL:$Coro::IDLE blocked itself"), but this is just best effort and
687only works when you do not run your own event loop.
660 688
661This function allows your callbacks to block by executing them in another 689This function allows your callbacks to block by executing them in another
662coro where it is safe to block. One example where blocking is handy 690coro where it is safe to block. One example where blocking is handy
663is when you use the L<Coro::AIO|Coro::AIO> functions to save results to 691is when you use the L<Coro::AIO|Coro::AIO> functions to save results to
664disk, for example. 692disk, for example.
706 unshift @unblock_queue, [$cb, @_]; 734 unshift @unblock_queue, [$cb, @_];
707 $unblock_scheduler->ready; 735 $unblock_scheduler->ready;
708 } 736 }
709} 737}
710 738
711=item $cb = Coro::rouse_cb 739=item $cb = rouse_cb
712 740
713Create and return a "rouse callback". That's a code reference that, 741Create and return a "rouse callback". That's a code reference that,
714when called, will remember a copy of its arguments and notify the owner 742when called, will remember a copy of its arguments and notify the owner
715coro of the callback. 743coro of the callback.
716 744
717See the next function. 745See the next function.
718 746
719=item @args = Coro::rouse_wait [$cb] 747=item @args = rouse_wait [$cb]
720 748
721Wait for the specified rouse callback (or the last one that was created in 749Wait for the specified rouse callback (or the last one that was created in
722this coro). 750this coro).
723 751
724As soon as the callback is invoked (or when the callback was invoked 752As soon as the callback is invoked (or when the callback was invoked
725before C<rouse_wait>), it will return the arguments originally passed to 753before C<rouse_wait>), it will return the arguments originally passed to
726the rouse callback. 754the rouse callback. In scalar context, that means you get the I<last>
755argument, just as if C<rouse_wait> had a C<return ($a1, $a2, $a3...)>
756statement at the end.
727 757
728See the section B<HOW TO WAIT FOR A CALLBACK> for an actual usage example. 758See the section B<HOW TO WAIT FOR A CALLBACK> for an actual usage example.
729 759
730=back 760=back
731 761
732=cut 762=cut
763
764for my $module (qw(Channel RWLock Semaphore SemaphoreSet Signal Specific)) {
765 my $old = defined &{"Coro::$module\::new"} && \&{"Coro::$module\::new"};
766
767 *{"Coro::$module\::new"} = sub {
768 require "Coro/$module.pm";
769
770 # some modules have their new predefined in State.xs, some don't
771 *{"Coro::$module\::new"} = $old
772 if $old;
773
774 goto &{"Coro::$module\::new"};
775 };
776}
733 777
7341; 7781;
735 779
736=head1 HOW TO WAIT FOR A CALLBACK 780=head1 HOW TO WAIT FOR A CALLBACK
737 781
819the windows process emulation enabled under unix roughly halves perl 863the windows process emulation enabled under unix roughly halves perl
820performance, even when not used. 864performance, even when not used.
821 865
822=item coro switching is not signal safe 866=item coro switching is not signal safe
823 867
824You must not switch to another coro from within a signal handler 868You must not switch to another coro from within a signal handler (only
825(only relevant with %SIG - most event libraries provide safe signals). 869relevant with %SIG - most event libraries provide safe signals), I<unless>
870you are sure you are not interrupting a Coro function.
826 871
827That means you I<MUST NOT> call any function that might "block" the 872That means you I<MUST NOT> call any function that might "block" the
828current coro - C<cede>, C<schedule> C<< Coro::Semaphore->down >> or 873current coro - C<cede>, C<schedule> C<< Coro::Semaphore->down >> or
829anything that calls those. Everything else, including calling C<ready>, 874anything that calls those. Everything else, including calling C<ready>,
830works. 875works.
831 876
832=back 877=back
833 878
834 879
880=head1 WINDOWS PROCESS EMULATION
881
882A great many people seem to be confused about ithreads (for example, Chip
883Salzenberg called me unintelligent, incapable, stupid and gullible,
884while in the same mail making rather confused statements about perl
885ithreads (for example, that memory or files would be shared), showing his
886lack of understanding of this area - if it is hard to understand for Chip,
887it is probably not obvious to everybody).
888
889What follows is an ultra-condensed version of my talk about threads in
890scripting languages given on the perl workshop 2009:
891
892The so-called "ithreads" were originally implemented for two reasons:
893first, to (badly) emulate unix processes on native win32 perls, and
894secondly, to replace the older, real thread model ("5.005-threads").
895
896It does that by using threads instead of OS processes. The difference
897between processes and threads is that threads share memory (and other
898state, such as files) between threads within a single process, while
899processes do not share anything (at least not semantically). That
900means that modifications done by one thread are seen by others, while
901modifications by one process are not seen by other processes.
902
903The "ithreads" work exactly like that: when creating a new ithreads
904process, all state is copied (memory is copied physically, files and code
905is copied logically). Afterwards, it isolates all modifications. On UNIX,
906the same behaviour can be achieved by using operating system processes,
907except that UNIX typically uses hardware built into the system to do this
908efficiently, while the windows process emulation emulates this hardware in
909software (rather efficiently, but of course it is still much slower than
910dedicated hardware).
911
912As mentioned before, loading code, modifying code, modifying data
913structures and so on is only visible in the ithreads process doing the
914modification, not in other ithread processes within the same OS process.
915
916This is why "ithreads" do not implement threads for perl at all, only
917processes. What makes it so bad is that on non-windows platforms, you can
918actually take advantage of custom hardware for this purpose (as evidenced
919by the forks module, which gives you the (i-) threads API, just much
920faster).
921
922Sharing data is in the i-threads model is done by transfering data
923structures between threads using copying semantics, which is very slow -
924shared data simply does not exist. Benchmarks using i-threads which are
925communication-intensive show extremely bad behaviour with i-threads (in
926fact, so bad that Coro, which cannot take direct advantage of multiple
927CPUs, is often orders of magnitude faster because it shares data using
928real threads, refer to my talk for details).
929
930As summary, i-threads *use* threads to implement processes, while
931the compatible forks module *uses* processes to emulate, uhm,
932processes. I-threads slow down every perl program when enabled, and
933outside of windows, serve no (or little) practical purpose, but
934disadvantages every single-threaded Perl program.
935
936This is the reason that I try to avoid the name "ithreads", as it is
937misleading as it implies that it implements some kind of thread model for
938perl, and prefer the name "windows process emulation", which describes the
939actual use and behaviour of it much better.
940
835=head1 SEE ALSO 941=head1 SEE ALSO
836 942
837Event-Loop integration: L<Coro::AnyEvent>, L<Coro::EV>, L<Coro::Event>. 943Event-Loop integration: L<Coro::AnyEvent>, L<Coro::EV>, L<Coro::Event>.
838 944
839Debugging: L<Coro::Debug>. 945Debugging: L<Coro::Debug>.

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines