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

Comparing Coro/Coro/AnyEvent.pm (file contents):
Revision 1.39 by root, Sat Jun 20 07:16:31 2009 UTC vs.
Revision 1.40 by root, Mon Jun 22 11:25:53 2009 UTC

31This module autodetects the event loop used (by relying on L<AnyEvent>) 31This module autodetects the event loop used (by relying on L<AnyEvent>)
32and will either automatically defer to the high-performance L<Coro::EV> or 32and will either automatically defer to the high-performance L<Coro::EV> or
33L<Coro::Event> modules, or will use a generic integration into any event 33L<Coro::Event> modules, or will use a generic integration into any event
34loop supported by L<AnyEvent>. 34loop supported by L<AnyEvent>.
35 35
36The effect on your threads (explained in more detail below) will be that 36Note that if you need to wait for a single event, the rouse functions will
37threads of the same or higher priority than the thread running the event 37come in handy (see the Coro manpage for details):
38loop will get as much CPU time as they want. If none exist, then threads
39of lower priority will also run, but after each of their time slices, the
40event loop will run to check for new events.
41 38
42That means that threads of equal or higher priority will starve the event 39 # wait for single SIGINT
43system unless they explicitly wait for an event, while those of lower 40 {
44priority will coexist with the event loop itself. 41 my $int_w = AnyEvent->signal (signal => "INT", cb => Coro::rouse_cb);
42 Coro::rouse_wait;
43 }
45 44
46For this reason, it is often beneficial to run the actual event loop at 45=head1 FUNCTIONS
47slightly elevated priority:
48 46
49 $Coro::current->nice (-1); 47Coro::AnyEvent offers a few functions that might be useful for
50 AnyEvent->loop; 48"background" threads:
51
52Also note that you actually I<have to run> an event loop for this
53priority scheme to work, as neither Coro::AnyEvent nor L<Coro::EV> or
54L<Coro::Event> will do that for you - those modules will check for events
55only when no other thread is runnable.
56
57The most logical place to run the event loop is usually at the end of the
58main program - start some threads, install some event watchers, then run
59the event loop of your choice.
60
61=head1 DETAILED DESCRIPTION
62
63Unfortunately, few event loops (basically only L<EV> and L<Event>)
64support the kind of integration required for smooth operations well, and
65consequently, AnyEvent cannot completely offer the functionality required
66by this module, so we need to improvise.
67
68Here is what this module does when it has to work with other event loops:
69 49
70=over 4 50=over 4
71
72=item * run ready threads before blocking the process
73
74Each time a thread is put into the ready queue (and there are no other
75threads in the ready queue), a timer with an C<after> value of C<0> is
76registered with AnyEvent.
77
78This creates something similar to an I<idle> watcher, i.e. a watcher
79that keeps the event loop from blocking but still polls for new
80events. (Unfortunately, some badly designed event loops (e.g. Event::Lib)
81don't support a timeout of C<0> and will always block for a bit).
82
83The callback for that timer will C<cede> to other threads of the same or
84higher priority for as long as such threads exists. This has the effect of
85running all threads that have work to do until all threads block to wait
86for external events.
87
88If no threads of equal or higher priority are ready, it will cede to any
89thread, but only once. This has the effect of running lower-priority
90threads as well, but it will not keep higher priority threads from
91receiving new events.
92
93The priority used is simply the priority of the thread that runs the event
94loop, usually the main program, which usually has a priority of C<0>.
95
96See "USAGE", above, for more details.
97
98=item * provide a suitable idle callback.
99
100In addition to hooking into C<ready>, this module will also provide a
101C<$Coro::idle> handler that runs the event loop. It is best not to take
102advantage of this too often, as this is rather inefficient, but it should
103work perfectly fine.
104
105=item * provide overrides for AnyEvent's condvars
106
107This module installs overrides for AnyEvent's condvars. That is, when
108the module is loaded it will provide its own condition variables. This
109makes them coroutine-safe, i.e. you can safely block on them from within a
110coroutine.
111
112=item * lead to data corruption or worse
113
114As C<unblock_sub> cannot be used by this module (as it is the module
115that implements it, basically), you must not call into the event
116loop recursively from any coroutine. This is not usually a difficult
117restriction to live with, just use condvars, C<unblock_sub> or other means
118of inter-coroutine-communications.
119
120If you use a module that supports AnyEvent (or uses the same event loop
121as AnyEvent, making the compatible), and it offers callbacks of any kind,
122then you must not block in them, either (or use e.g. C<unblock_sub>), see
123the description of C<unblock_sub> in the L<Coro> module.
124
125This also means that you should load the module as early as possible,
126as only condvars created after this module has been loaded will work
127correctly.
128
129=back
130 51
131=cut 52=cut
132 53
133package Coro::AnyEvent; 54package Coro::AnyEvent;
134 55
161 82
162 Coro::_set_readyhook undef; 83 Coro::_set_readyhook undef;
163 84
164 my $model = $AnyEvent::MODEL; 85 my $model = $AnyEvent::MODEL;
165 86
166 if ($model eq "AnyEvent::Impl::EV") { 87 if ($model eq "AnyEvent::Impl::EV" and eval { require Coro::EV }) {
167 require Coro::EV; 88 # provider faster versions of some functions
168 } elsif ($model eq "AnyEvent::Impl::Event") { 89
169 require Coro::Event; 90 eval '
91 *sleep = \&Coro::EV::timer_once;
92 *poll = \&Coro::EV::timer_once;
93 *idle = sub {
94 my $w = EV::idle Coro::rouse_cb;
95 Coro::rouse_wait;
96 };
97 *idle_upto = sub {
98 my $cb = Coro::rouse_cb;
99 my $t = EV::timer $_[0], 0, $cb;
100 my $w = EV::idle $cb;
101 Coro::rouse_wait;
102 };
103 *readable = sub {
104 EV::READ & Coro::EV::timed_io_once $_[0], EV::READ , $_[1]
105 };
106 *writable = sub {
107 EV::WRITE & Coro::EV::timed_io_once $_[0], EV::WRITE, $_[1]
108 };
109 ';
110 die if $@;
111
112 } elsif ($model eq "AnyEvent::Impl::Event" and eval { require Coro::Event }) {
113 # let Coro::Event do its thing
170 } else { 114 } else {
115 # do the inefficient thing ourselves
171 Coro::_set_readyhook \&_activity; 116 Coro::_set_readyhook \&_activity;
172 117
173 $IDLE = new Coro sub { 118 $IDLE = new Coro sub {
174 my $one_event = AnyEvent->can ("one_event"); 119 my $one_event = AnyEvent->can ("one_event");
120
175 while () { 121 while () {
176 $one_event->(); 122 $one_event->();
177 Coro::schedule; 123 Coro::schedule;
178 } 124 }
179 }; 125 };
181 127
182 $Coro::idle = $IDLE; 128 $Coro::idle = $IDLE;
183 } 129 }
184}; 130};
185 131
132=item Coro::AnyEvent::poll
133
134This call will block the current thread until the event loop has polled
135for new events and instructs the event loop to poll for new events once,
136without blocking.
137
138Note that this call will not actually execute the poll, just block until
139new events have been polled, so other threads will have a chance to run.
140
141This is useful when you have a thread that does some computations, but you
142still want to poll for new events from time to time. Simply call C<poll>
143from time to time:
144
145 my $long_calc = async {
146 for (1..10000) {
147 Coro::AnyEvent::poll:
148 # do some stuff, make sure it takes at least 0.001s or so
149 }
150 }
151
152Although you should also consider C<idle> or C<idle_upto> in such cases.
153
154=item Coro::AnyEvent::sleep $seconds
155
156This blocks the current thread for at least the given number of seconds.
157
158=item Coro::AnyEvent::idle
159
160This call is similar to C<poll> in that it will also poll for
161events. Unlike C<poll>, it will only resume the thread once there are no
162events to handle anymore, i.e. when the process is otherwise idle.
163
164=item Coro::AnyEvent::idle_upto $seconds
165
166Like C<idle>, but with a maximum waiting time.
167
168If your process is busy handling events, calling C<idle> can mean that
169your thread will never be resumed. To avoid this, you can use C<idle_upto>
170and specify a timeout, after which your thread will be resumed even if the
171process is completely busy.
172
173=item Coro::AnyEvent::readable $fh[, $timeout]
174
175=item Coro::AnyEvent::writable $fh[, $timeout]
176
177Blocks the current thread until the given file handle (not file
178descriptor) becomes readable (or writable), or the given timeout has
179elapsed, whichever happens first. No timeout counts as infinite timeout.
180
181Returns true when the file handle became ready, false when a timeout
182occured.
183
184Note that these functions are quite inefficient as compared to using a
185single watcher (they recreate watchers on every invocation) or compared to
186using Coro::Handle.
187
188Note also that they only work for sources that have reasonable
189non-blocking behaviour (e.g. not files).
190
191Example: wait until STDIN becomes readable, then quit the program.
192
193 use Coro::AnyEvent;
194 print "press enter to quit...\n";
195 Coro::AnyEvent::readable *STDIN;
196 exit 0;
197
198=cut
199
200sub poll() {
201 my $w = AnyEvent->timer (after => 0, cb => Coro::rouse_cb);
202 Coro::rouse_wait;
203}
204
205sub sleep($) {
206 my $w = AnyEvent->timer (after => $_[0], cb => Coro::rouse_cb);
207 Coro::rouse_wait;
208}
209
210sub idle() {
211 my $w = AnyEvent->idle (cb => Coro::rouse_cb);
212 Coro::rouse_wait;
213}
214
215sub idle_upto($) {
216 my $cb = Coro::rouse_cb;
217 my $t = AnyEvent->timer (after => shift, cb => $cb);
218 my $w = AnyEvent->idle (cb => $cb);
219 Coro::rouse_wait;
220}
221
222sub readable($;$) {
223 my $cb = Coro::rouse_cb;
224 my $w = AnyEvent->io (fh => $_[0], poll => "r", cb => sub { $cb->(1) });
225 my $t = defined $_[1] && AnyEvent->timer (after => $_[1], cb => sub { $cb->(0) });
226 Coro::rouse_wait
227}
228
229sub writable($;$) {
230 my $cb = Coro::rouse_cb;
231 my $w = AnyEvent->io (fh => $_[0], poll => "w", cb => sub { $cb->(1) });
232 my $t = defined $_[1] && AnyEvent->timer (after => $_[1], cb => sub { $cb->(0) });
233 Coro::rouse_wait
234}
235
186############################################################################# 236#############################################################################
187# override condvars 237# override condvars
188 238
189package Coro::AnyEvent::CondVar; 239package Coro::AnyEvent::CondVar;
190 240
199 } 249 }
200} 250}
201 251
2021; 2521;
203 253
254=back
255
256=head1 IMPLEMENTATION DETAILS
257
258Unfortunately, few event loops (basically only L<EV> and L<Event>)
259support the kind of integration required for smooth operations well, and
260consequently, AnyEvent cannot completely offer the functionality required
261by this module, so we need to improvise.
262
263Here is what this module does when it has to work with other event loops:
264
265=over 4
266
267=item * run ready threads before blocking the process
268
269Each time a thread is put into the ready queue (and there are no other
270threads in the ready queue), a timer with an C<after> value of C<0> is
271registered with AnyEvent.
272
273This creates something similar to an I<idle> watcher, i.e. a watcher
274that keeps the event loop from blocking but still polls for new
275events. (Unfortunately, some badly designed event loops (e.g. Event::Lib)
276don't support a timeout of C<0> and will always block for a bit).
277
278The callback for that timer will C<cede> to other threads of the same or
279higher priority for as long as such threads exists. This has the effect of
280running all threads that have work to do until all threads block to wait
281for external events.
282
283If no threads of equal or higher priority are ready, it will cede to any
284thread, but only once. This has the effect of running lower-priority
285threads as well, but it will not keep higher priority threads from
286receiving new events.
287
288The priority used is simply the priority of the thread that runs the event
289loop, usually the main program, which usually has a priority of C<0>. Note
290that Coro::AnyEvent does I<not> run an event loop for you, so unless the
291main program runs one, there will simply be no event loop to C<cede> to
292(event handling will still work, somewhat inefficiently, but any thread
293will have a higher priority than event handling in that case).
294
295=item * provide a suitable idle callback.
296
297In addition to hooking into C<ready>, this module will also provide a
298C<$Coro::idle> handler that runs the event loop. It is best not to take
299advantage of this too often, as this is rather inefficient, but it should
300work perfectly fine.
301
302=item * provide overrides for AnyEvent's condvars
303
304This module installs overrides for AnyEvent's condvars. That is, when
305the module is loaded it will provide its own condition variables. This
306makes them coroutine-safe, i.e. you can safely block on them from within a
307coroutine.
308
309=item * lead to data corruption or worse
310
311As C<unblock_sub> cannot be used by this module (as it is the module
312that implements it, basically), you must not call into the event
313loop recursively from any coroutine. This is not usually a difficult
314restriction to live with, just use condvars, C<unblock_sub> or other means
315of inter-coroutine-communications.
316
317If you use a module that supports AnyEvent (or uses the same event loop
318as AnyEvent, making the compatible), and it offers callbacks of any kind,
319then you must not block in them, either (or use e.g. C<unblock_sub>), see
320the description of C<unblock_sub> in the L<Coro> module.
321
322This also means that you should load the module as early as possible,
323as only condvars created after this module has been loaded will work
324correctly.
325
326=back
327
204=head1 SEE ALSO 328=head1 SEE ALSO
205 329
206L<AnyEvent>, to see which event loops are supported, L<Coro::EV> and 330L<AnyEvent>, to see which event loops are supported, L<Coro::EV> and
207L<Coro::Event> for more efficient and more correct solutions (they will be 331L<Coro::Event> for more efficient and more correct solutions (they will be
208used automatically if applicable). 332used automatically if applicable).

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines