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

Comparing Coro/Coro.pm (file contents):
Revision 1.297 by root, Thu May 12 23:55:39 2011 UTC vs.
Revision 1.321 by root, Sun Feb 2 03:26:06 2014 UTC

16 cede; # yield to coro 16 cede; # yield to coro
17 print "3\n"; 17 print "3\n";
18 cede; # and again 18 cede; # and again
19 19
20 # use locking 20 # use locking
21 use Coro::Semaphore;
22 my $lock = new Coro::Semaphore; 21 my $lock = new Coro::Semaphore;
23 my $locked; 22 my $locked;
24 23
25 $lock->down; 24 $lock->down;
26 $locked = 1; 25 $locked = 1;
196 195
197 async { 196 async {
198 Coro::terminate "return value 1", "return value 2"; 197 Coro::terminate "return value 1", "return value 2";
199 }; 198 };
200 199
201And yet another way is to C<< ->cancel >> (or C<< ->safe_cancel >>) the 200Yet another way is to C<< ->cancel >> (or C<< ->safe_cancel >>) the coro
202coro thread from another thread: 201thread from another thread:
203 202
204 my $coro = async { 203 my $coro = async {
205 exit 1; 204 exit 1;
206 }; 205 };
207 206
219So, cancelling a thread that runs in an XS event loop might not be the 218So, cancelling a thread that runs in an XS event loop might not be the
220best idea, but any other combination that deals with perl only (cancelling 219best idea, but any other combination that deals with perl only (cancelling
221when a thread is in a C<tie> method or an C<AUTOLOAD> for example) is 220when a thread is in a C<tie> method or an C<AUTOLOAD> for example) is
222safe. 221safe.
223 222
224Lastly, a coro thread object that isn't referenced is C<< ->cancel >>'ed 223Last not least, a coro thread object that isn't referenced is C<<
225automatically - just like other objects in Perl. This is not such a common 224->cancel >>'ed automatically - just like other objects in Perl. This
226case, however - a running thread is referencedy b C<$Coro::current>, a 225is not such a common case, however - a running thread is referencedy by
227thread ready to run is referenced by the ready queue, a thread waiting 226C<$Coro::current>, a thread ready to run is referenced by the ready queue,
228on a lock or semaphore is referenced by being in some wait list and so 227a thread waiting on a lock or semaphore is referenced by being in some
229on. But a thread that isn't in any of those queues gets cancelled: 228wait list and so on. But a thread that isn't in any of those queues gets
229cancelled:
230 230
231 async { 231 async {
232 schedule; # cede to other coros, don't go into the ready queue 232 schedule; # cede to other coros, don't go into the ready queue
233 }; 233 };
234 234
235 cede; 235 cede;
236 # now the async above is destroyed, as it is not referenced by anything. 236 # now the async above is destroyed, as it is not referenced by anything.
237
238A slightly embellished example might make it clearer:
239
240 async {
241 my $guard = Guard::guard { print "destroyed\n" };
242 schedule while 1;
243 };
244
245 cede;
246
247Superficially one might not expect any output - since the C<async>
248implements an endless loop, the C<$guard> will not be cleaned up. However,
249since the thread object returned by C<async> is not stored anywhere, the
250thread is initially referenced because it is in the ready queue, when it
251runs it is referenced by C<$Coro::current>, but when it calls C<schedule>,
252it gets C<cancel>ed causing the guard object to be destroyed (see the next
253section), and printing it's message.
254
255If this seems a bit drastic, remember that this only happens when nothing
256references the thread anymore, which means there is no way to further
257execute it, ever. The only options at this point are leaking the thread,
258or cleaning it up, which brings us to...
237 259
238=item 5. Cleanup 260=item 5. Cleanup
239 261
240Threads will allocate various resources. Most but not all will be returned 262Threads will allocate various resources. Most but not all will be returned
241when a thread terminates, during clean-up. 263when a thread terminates, during clean-up.
260 282
261 my $sem = new Coro::Semaphore; 283 my $sem = new Coro::Semaphore;
262 284
263 async { 285 async {
264 my $lock_guard = $sem->guard; 286 my $lock_guard = $sem->guard;
265 # if we reutrn, or die or get cancelled, here, 287 # if we return, or die or get cancelled, here,
266 # then the semaphore will be "up"ed. 288 # then the semaphore will be "up"ed.
267 }; 289 };
268 290
269The C<Guard::guard> function comes in handy for any custom cleanup you 291The C<Guard::guard> function comes in handy for any custom cleanup you
270might want to do (but you cannot switch to other coroutines form those 292might want to do (but you cannot switch to other coroutines from those
271code blocks): 293code blocks):
272 294
273 async { 295 async {
274 my $window = new Gtk2::Window "toplevel"; 296 my $window = new Gtk2::Window "toplevel";
275 # The window will not be cleaned up automatically, even when $window 297 # The window will not be cleaned up automatically, even when $window
292=item 6. Viva La Zombie Muerte 314=item 6. Viva La Zombie Muerte
293 315
294Even after a thread has terminated and cleaned up its resources, the Coro 316Even after a thread has terminated and cleaned up its resources, the Coro
295object still is there and stores the return values of the thread. 317object still is there and stores the return values of the thread.
296 318
297The means the Coro object gets freed automatically when the thread has 319When there are no other references, it will simply be cleaned up and
298terminated and cleaned up and there arenot other references. 320freed.
299 321
300If there are, the Coro object will stay around, and you can call C<< 322If there areany references, the Coro object will stay around, and you
301->join >> as many times as you wish to retrieve the result values: 323can call C<< ->join >> as many times as you wish to retrieve the result
324values:
302 325
303 async { 326 async {
304 print "hi\n"; 327 print "hi\n";
305 1 328 1
306 }; 329 };
343 366
344our $idle; # idle handler 367our $idle; # idle handler
345our $main; # main coro 368our $main; # main coro
346our $current; # current coro 369our $current; # current coro
347 370
348our $VERSION = 5.372; 371our $VERSION = 6.33;
349 372
350our @EXPORT = qw(async async_pool cede schedule terminate current unblock_sub rouse_cb rouse_wait); 373our @EXPORT = qw(async async_pool cede schedule terminate current unblock_sub rouse_cb rouse_wait);
351our %EXPORT_TAGS = ( 374our %EXPORT_TAGS = (
352 prio => [qw(PRIO_MAX PRIO_HIGH PRIO_NORMAL PRIO_LOW PRIO_IDLE PRIO_MIN)], 375 prio => [qw(PRIO_MAX PRIO_HIGH PRIO_NORMAL PRIO_LOW PRIO_IDLE PRIO_MIN)],
353); 376);
358=over 4 381=over 4
359 382
360=item $Coro::main 383=item $Coro::main
361 384
362This variable stores the Coro object that represents the main 385This variable stores the Coro object that represents the main
363program. While you cna C<ready> it and do most other things you can do to 386program. While you can C<ready> it and do most other things you can do to
364coro, it is mainly useful to compare again C<$Coro::current>, to see 387coro, it is mainly useful to compare again C<$Coro::current>, to see
365whether you are running in the main program or not. 388whether you are running in the main program or not.
366 389
367=cut 390=cut
368 391
767current Coro. 790current Coro.
768 791
769This is a rather brutal way to free a coro, with some limitations - if 792This is a rather brutal way to free a coro, with some limitations - if
770the thread is inside a C callback that doesn't expect to be canceled, 793the thread is inside a C callback that doesn't expect to be canceled,
771bad things can happen, or if the cancelled thread insists on running 794bad things can happen, or if the cancelled thread insists on running
772complicated cleanup handlers that rely on it'S thread context, things will 795complicated cleanup handlers that rely on its thread context, things will
773not work. 796not work.
774 797
775Any cleanup code being run (e.g. from C<guard> blocks) will be run without 798Any cleanup code being run (e.g. from C<guard> blocks) will be run without
776a thread context, and is not allowed to switch to other threads. On the 799a thread context, and is not allowed to switch to other threads. On the
777plus side, C<< ->cancel >> will always clean up the thread, no matter 800plus side, C<< ->cancel >> will always clean up the thread, no matter
891that is, after it's resources have been freed but before it is joined. The 914that is, after it's resources have been freed but before it is joined. The
892callback gets passed the terminate/cancel arguments, if any, and I<must 915callback gets passed the terminate/cancel arguments, if any, and I<must
893not> die, under any circumstances. 916not> die, under any circumstances.
894 917
895There can be any number of C<on_destroy> callbacks per coro, and there is 918There can be any number of C<on_destroy> callbacks per coro, and there is
896no way currently to remove a callback once added. 919currently no way to remove a callback once added.
897 920
898=item $oldprio = $coro->prio ($newprio) 921=item $oldprio = $coro->prio ($newprio)
899 922
900Sets (or gets, if the argument is missing) the priority of the 923Sets (or gets, if the argument is missing) the priority of the
901coro thread. Higher priority coro get run before lower priority 924coro thread. Higher priority coro get run before lower priority
928coro thread. This is just a free-form string you can associate with a 951coro thread. This is just a free-form string you can associate with a
929coro. 952coro.
930 953
931This method simply sets the C<< $coro->{desc} >> member to the given 954This method simply sets the C<< $coro->{desc} >> member to the given
932string. You can modify this member directly if you wish, and in fact, this 955string. You can modify this member directly if you wish, and in fact, this
933is often preferred to indicate major processing states that cna then be 956is often preferred to indicate major processing states that can then be
934seen for example in a L<Coro::Debug> session: 957seen for example in a L<Coro::Debug> session:
935 958
936 sub my_long_function { 959 sub my_long_function {
937 local $Coro::current->{desc} = "now in my_long_function"; 960 local $Coro::current->{desc} = "now in my_long_function";
938 ... 961 ...
1107But from within a coro, you often just want to write this: 1130But from within a coro, you often just want to write this:
1108 1131
1109 my $status = wait_for_child $pid; 1132 my $status = wait_for_child $pid;
1110 1133
1111Coro offers two functions specifically designed to make this easy, 1134Coro offers two functions specifically designed to make this easy,
1112C<Coro::rouse_cb> and C<Coro::rouse_wait>. 1135C<rouse_cb> and C<rouse_wait>.
1113 1136
1114The first function, C<rouse_cb>, generates and returns a callback that, 1137The first function, C<rouse_cb>, generates and returns a callback that,
1115when invoked, will save its arguments and notify the coro that 1138when invoked, will save its arguments and notify the coro that
1116created the callback. 1139created the callback.
1117 1140
1123function mentioned above: 1146function mentioned above:
1124 1147
1125 sub wait_for_child($) { 1148 sub wait_for_child($) {
1126 my ($pid) = @_; 1149 my ($pid) = @_;
1127 1150
1128 my $watcher = AnyEvent->child (pid => $pid, cb => Coro::rouse_cb); 1151 my $watcher = AnyEvent->child (pid => $pid, cb => rouse_cb);
1129 1152
1130 my ($rpid, $rstatus) = Coro::rouse_wait; 1153 my ($rpid, $rstatus) = rouse_wait;
1131 $rstatus 1154 $rstatus
1132 } 1155 }
1133 1156
1134In the case where C<rouse_cb> and C<rouse_wait> are not flexible enough, 1157In the case where C<rouse_cb> and C<rouse_wait> are not flexible enough,
1135you can roll your own, using C<schedule>: 1158you can roll your own, using C<schedule> and C<ready>:
1136 1159
1137 sub wait_for_child($) { 1160 sub wait_for_child($) {
1138 my ($pid) = @_; 1161 my ($pid) = @_;
1139 1162
1140 # store the current coro in $current, 1163 # store the current coro in $current,
1143 my ($done, $rstatus); 1166 my ($done, $rstatus);
1144 1167
1145 # pass a closure to ->child 1168 # pass a closure to ->child
1146 my $watcher = AnyEvent->child (pid => $pid, cb => sub { 1169 my $watcher = AnyEvent->child (pid => $pid, cb => sub {
1147 $rstatus = $_[1]; # remember rstatus 1170 $rstatus = $_[1]; # remember rstatus
1148 $done = 1; # mark $rstatus as valud 1171 $done = 1; # mark $rstatus as valid
1172 $current->ready; # wake up the waiting thread
1149 }); 1173 });
1150 1174
1151 # wait until the closure has been called 1175 # wait until the closure has been called
1152 schedule while !$done; 1176 schedule while !$done;
1153 1177

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines