1AnyEvent(3) User Contributed Perl Documentation AnyEvent(3)
2
3
4
6 Coro::AnyEvent - integrate threads into AnyEvent
7
9 use Coro;
10 use AnyEvent;
11 # using both Coro and AnyEvent will automatically load Coro::AnyEvent
12
13 # or load it manually for its utility functions:
14 use Coro::AnyEvent;
15
16 Coro::AnyEvent::sleep 5; # block current thread for 5s
17 Coro::AnyEvent::poll; # poll for new events once
18 Coro::AnyEvent::idle; # block until process no longer busy
19 Coro::AnyEvent::idle_upto 5; # same, but only up to 5 seconds
20
21 Coro::AnyEvent::readable $fh, 60
22 or die "fh didn't become readable within 60 seconds\n";
23
25 When one naively starts to use threads in Perl, one will quickly run
26 into the problem that threads which block on a syscall (sleeping,
27 reading from a socket etc.) will block all threads.
28
29 If one then uses an event loop, the problem is that the event loop has
30 no knowledge of threads and will not run them before it polls for new
31 events, again blocking the whole process.
32
33 This module integrates threads into any event loop supported by
34 AnyEvent, combining event-based programming with coroutine-based
35 programming in a natural way.
36
37 As of Coro 5.21 and newer, this module gets loaded automatically when
38 AnyEvent initialises itself and Coro is used in the same process, thus
39 there is no need to load it manually if you just want your threads to
40 coexist with AnyEvent.
41
42 If you want to use any functions from this module, you of course still
43 need to "use Coro::AnyEvent", just as with other perl modules.
44
45 Also, this module autodetects the event loop used (by relying on
46 AnyEvent) and will either automatically defer to the high-performance
47 Coro::EV or Coro::Event modules, or will use a generic integration
48 method that should work with any event loop supported by AnyEvent.
49
51 RUN AN EVENT LOOP - OR NOT?
52 For performance reasons, it is recommended that the main program or
53 something else run the event loop of the event model you use, i.e.
54
55 use Gtk2; # <- the event model
56 use AnyEvent;
57 use Coro:
58
59 # initialise stuff
60 async { ... };
61
62 # now run mainloop of Gtk2
63 main Gtk2;
64
65 You can move the event loop into a thread as well, although this tends
66 to get confusing:
67
68 use Gtk2;
69 use AnyEvent;
70 use Coro:
71
72 async { main Gtk2 };
73
74 # do other things...
75 while () {
76 use Coro::AnyEvent;
77 Coro::AnyEvent::sleep 1;
78 print "ping...\n";
79 }
80
81 You can also do nothing, in which case Coro::AnyEvent will invoke the
82 event loop as needed, which is less efficient, but sometimes very
83 convenient.
84
85 What you MUST NOT EVER DO is to block inside an event loop callback.
86 The reason is that most event loops are not reentrant and this can
87 cause a deadlock at best and corrupt memory at worst.
88
89 Coro will try to catch you when you block in the event loop ("FATAL:
90 $Coro::IDLE blocked itself"), but this is just best effort and only
91 works when you do not run your own event loop.
92
93 To avoid this problem, start a new thread (e.g. with
94 "Coro::async_pool") or use "Coro::unblock_sub" to run blocking tasks.
95
96 INVERSION OF CONTROL
97 If you need to wait for a single event, the rouse functions will come
98 in handy (see the Coro manpage for details):
99
100 # wait for single SIGINT
101 {
102 my $int_w = AnyEvent->signal (signal => "INT", cb => Coro::rouse_cb);
103 Coro::rouse_wait;
104 }
105
106 EVENT MODULES OTHER THAN ANYEVENT
107 Keep in mind that, as shipped, Coro and Coro::AnyEvent only work with
108 AnyEvent, and only when AnyEvent is actually used (i.e. initialised),
109 so this will not work:
110
111 # does not work: EV without AnyEvent is not recognised
112 use EV;
113 use Coro;
114
115 EV::loop;
116
117 And neither does this, unless you actually use AnyEvent for something:
118
119 # does not work: AnyEvent must be initialised (e.g. by creating watchers)
120 use EV;
121 use AnyEvent;
122 use Coro;
123
124 EV::loop;
125
126 This does work, however, because you create a watcher (condvars work,
127 too), thus forcing AnyEvent to initialise itself:
128
129 # does work: AnyEvent is actually used
130 use EV;
131 use AnyEvent;
132 use Coro;
133
134 my $timer = AE::timer 1, 1, sub { };
135
136 EV::loop;
137
138 And if you want to use AnyEvent just to bridge between Coro and your
139 event model of choice, you can simply force it to initialise itself,
140 like this:
141
142 # does work: AnyEvent is initialised manually
143 use POE;
144 use AnyEvent;
145 use Coro;
146
147 AnyEvent::detect; # force AnyEvent to integrate Coro into POE
148 POE::Kernel->run;
149
151 Coro::AnyEvent also offers a few functions that might be useful.
152
153 Coro::AnyEvent::poll
154 This call will block the current thread until the event loop has
155 polled for potential new events and instructs the event loop to
156 poll for new events once, without blocking.
157
158 Note that this call will not actually execute the poll, nor will it
159 wait until there are some events, just block until the event loop
160 has polled for new events, so other threads will have a chance to
161 run.
162
163 This is useful when you have a thread that does some computations,
164 but you still want to poll for new events from time to time. Simply
165 call "poll" from time to time:
166
167 my $long_calc = async {
168 for (1..10000) {
169 Coro::AnyEvent::poll;
170 # do some stuff, make sure it takes at least 0.001s or so
171 }
172 }
173
174 Although you should also consider "idle" or "idle_upto" in such
175 cases.
176
177 Coro::AnyEvent::sleep $seconds
178 This blocks the current thread for at least the given number of
179 seconds.
180
181 Coro::AnyEvent::idle
182 This call is similar to "poll" in that it will also poll for
183 events. Unlike "poll", it will only resume the thread once there
184 are no events to handle anymore, i.e. when the process is otherwise
185 idle.
186
187 This is good for background threads that shouldn't use CPU time
188 when foreground jobs are ready to run.
189
190 Coro::AnyEvent::idle_upto $seconds
191 Like "idle", but with a maximum waiting time.
192
193 If your process is busy handling events, calling "idle" can mean
194 that your thread will never be resumed. To avoid this, you can use
195 "idle_upto" and specify a timeout, after which your thread will be
196 resumed even if the process is completely busy.
197
198 Coro::AnyEvent::readable $fh_or_fileno[, $timeout]
199 Coro::AnyEvent::writable $fh_or_fileno[, $timeout]
200 Blocks the current thread until the given file handle (or file
201 descriptor) becomes readable (or writable), or the given timeout
202 has elapsed, whichever happens first. No timeout counts as infinite
203 timeout.
204
205 Returns true when the file handle became ready, false when a
206 timeout occurred.
207
208 Note that these functions are quite inefficient as compared to
209 using a single watcher (they recreate watchers on every invocation)
210 or compared to using Coro::Handle.
211
212 Note also that they only work for sources that have reasonable non-
213 blocking behaviour (e.g. not files).
214
215 Example: wait until STDIN becomes readable, then quit the program.
216
217 use Coro::AnyEvent;
218 print "press enter to quit...\n";
219 Coro::AnyEvent::readable *STDIN;
220 exit 0;
221
223 Unfortunately, few event loops (basically only EV and Event) support
224 the kind of integration required for smooth operations well, and
225 consequently, AnyEvent cannot completely offer the functionality
226 required by this module, so we need to improvise.
227
228 Here is what this module does when it has to work with other event
229 loops:
230
231 · run ready threads before blocking the process
232
233 Each time a thread is put into the ready queue (and there are no
234 other threads in the ready queue), a timer with an "after" value of
235 0 is registered with AnyEvent.
236
237 This creates something similar to an idle watcher, i.e. a watcher
238 that keeps the event loop from blocking but still polls for new
239 events. (Unfortunately, some badly designed event loops (e.g.
240 Event::Lib) don't support a timeout of 0 and will always block for
241 a bit).
242
243 The callback for that timer will "cede" to other threads of the
244 same or higher priority for as long as such threads exists. This
245 has the effect of running all threads that have work to do until
246 all threads block to wait for external events.
247
248 If no threads of equal or higher priority are ready, it will cede
249 to any thread, but only once. This has the effect of running lower-
250 priority threads as well, but it will not keep higher priority
251 threads from receiving new events.
252
253 The priority used is simply the priority of the thread that runs
254 the event loop, usually the main program, which usually has a
255 priority of 0. Note that Coro::AnyEvent does not run an event loop
256 for you, so unless the main program runs one, there will simply be
257 no event loop to "cede" to (event handling will still work,
258 somewhat inefficiently, but any thread will have a higher priority
259 than event handling in that case).
260
261 · provide a suitable idle callback.
262
263 In addition to hooking into "ready", this module will also provide
264 a $Coro::idle handler that runs the event loop. It is best not to
265 take advantage of this too often, as this is rather inefficient,
266 but it should work perfectly fine.
267
268 · provide overrides for AnyEvent's condvars
269
270 This module installs overrides for AnyEvent's condvars. That is,
271 when the module is loaded it will provide its own condition
272 variables. This makes them coroutine-safe, i.e. you can safely
273 block on them from within a coroutine.
274
275 · lead to data corruption or worse
276
277 As "unblock_sub" cannot be used by this module (as it is the module
278 that implements it, basically), you must not call into the event
279 loop recursively from any coroutine. This is not usually a
280 difficult restriction to live with, just use condvars,
281 "unblock_sub" or other means of inter-coroutine-communications.
282
283 If you use a module that supports AnyEvent (or uses the same event
284 loop as AnyEvent, making it implicitly compatible), and it offers
285 callbacks of any kind, then you must not block in them, either (or
286 use e.g. "unblock_sub"), see the description of "unblock_sub" in
287 the Coro module.
288
289 This also means that you should load the module as early as
290 possible, as only condvars created after this module has been
291 loaded will work correctly.
292
294 AnyEvent, to see which event loops are supported, Coro::EV and
295 Coro::Event for more efficient and more correct solutions (they will be
296 used automatically if applicable).
297
299 Marc A. Lehmann <schmorp@schmorp.de>
300 http://software.schmorp.de/pkg/Coro.html
301
302
303
304perl v5.30.1 2020-01-29 AnyEvent(3)