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

Comparing Coro/README (file contents):
Revision 1.11 by root, Sat Oct 6 19:25:00 2007 UTC vs.
Revision 1.14 by root, Sat May 10 22:32:40 2008 UTC

1NAME 1NAME
2 Coro - coroutine process abstraction 2 Coro - coroutine process abstraction
3 3
4SYNOPSIS 4SYNOPSIS
5 use Coro; 5 use Coro;
6 6
7 async { 7 async {
8 # some asynchronous thread of execution 8 # some asynchronous thread of execution
9 print "2\n";
10 cede; # yield back to main
11 print "4\n";
9 }; 12 };
10 13 print "1\n";
11 # alternatively create an async coroutine like this: 14 cede; # yield to coroutine
12 15 print "3\n";
13 sub some_func : Coro { 16 cede; # and again
14 # some more async code
15 } 17
16 18 # use locking
17 cede; 19 my $lock = new Coro::Semaphore;
20 my $locked;
21
22 $lock->down;
23 $locked = 1;
24 $lock->up;
18 25
19DESCRIPTION 26DESCRIPTION
20 This module collection manages coroutines. Coroutines are similar to 27 This module collection manages coroutines. Coroutines are similar to
21 threads but don't run in parallel at the same time even on SMP machines. 28 threads but don't (in general) run in parallel at the same time even on
22 The specific flavor of coroutine used in this module also guarantees you 29 SMP machines. The specific flavor of coroutine used in this module also
23 that it will not switch between coroutines unless necessary, at 30 guarantees you that it will not switch between coroutines unless
24 easily-identified points in your program, so locking and parallel access 31 necessary, at easily-identified points in your program, so locking and
25 are rarely an issue, making coroutine programming much safer than 32 parallel access are rarely an issue, making coroutine programming much
26 threads programming. 33 safer and easier than threads programming.
27 34
28 (Perl, however, does not natively support real threads but instead does 35 Unlike a normal perl program, however, coroutines allow you to have
29 a very slow and memory-intensive emulation of processes using threads. 36 multiple running interpreters that share data, which is especially
30 This is a performance win on Windows machines, and a loss everywhere 37 useful to code pseudo-parallel processes and for event-based
31 else). 38 programming, such as multiple HTTP-GET requests running concurrently.
39 See Coro::AnyEvent to learn more.
40
41 Coroutines are also useful because Perl has no support for threads (the
42 so called "threads" that perl offers are nothing more than the (bad)
43 process emulation coming from the Windows platform: On standard
44 operating systems they serve no purpose whatsoever, except by making
45 your programs slow and making them use a lot of memory. Best disable
46 them when building perl, or aks your software vendor/distributor to do
47 it for you).
32 48
33 In this module, coroutines are defined as "callchain + lexical variables 49 In this module, coroutines are defined as "callchain + lexical variables
34 + @_ + $_ + $@ + $/ + C stack), that is, a coroutine has its own 50 + @_ + $_ + $@ + $/ + C stack), that is, a coroutine has its own
35 callchain, its own set of lexicals and its own set of perls most 51 callchain, its own set of lexicals and its own set of perls most
36 important global variables. 52 important global variables (see Coro::State for more configuration).
37 53
38 $main 54 $Coro::main
39 This coroutine represents the main program. 55 This variable stores the coroutine object that represents the main
56 program. While you cna "ready" it and do most other things you can
57 do to coroutines, it is mainly useful to compare again
58 $Coro::current, to see wether you are running in the main program or
59 not.
40 60
41 $current (or as function: current) 61 $Coro::current
42 The current coroutine (the last coroutine switched to). The initial 62 The coroutine object representing the current coroutine (the last
63 coroutine that the Coro scheduler switched to). The initial value is
43 value is $main (of course). 64 $main (of course).
44 65
45 This variable is strictly *read-only*. It is provided for 66 This variable is strictly *read-only*. You can take copies of the
46 performance reasons. If performance is not essential you are 67 value stored in it and use it as any other coroutine object, but you
47 encouraged to use the "Coro::current" function instead. 68 must not otherwise modify the variable itself.
48 69
49 $idle 70 $Coro::idle
50 A callback that is called whenever the scheduler finds no ready 71 This variable is mainly useful to integrate Coro into event loops.
51 coroutines to run. The default implementation prints "FATAL: 72 It is usually better to rely on Coro::AnyEvent or L"Coro::EV", as
52 deadlock detected" and exits, because the program has no other way 73 this is pretty low-level functionality.
53 to continue. 74
75 This variable stores a callback that is called whenever the
76 scheduler finds no ready coroutines to run. The default
77 implementation prints "FATAL: deadlock detected" and exits, because
78 the program has no other way to continue.
54 79
55 This hook is overwritten by modules such as "Coro::Timer" and 80 This hook is overwritten by modules such as "Coro::Timer" and
56 "Coro::Event" to wait on an external event that hopefully wake up a 81 "Coro::AnyEvent" to wait on an external event that hopefully wake up
57 coroutine so the scheduler can run it. 82 a coroutine so the scheduler can run it.
83
84 Note that the callback *must not*, under any circumstances, block
85 the current coroutine. Normally, this is achieved by having an "idle
86 coroutine" that calls the event loop and then blocks again, and then
87 readying that coroutine in the idle handler.
88
89 See Coro::Event or Coro::AnyEvent for examples of using this
90 technique.
58 91
59 Please note that if your callback recursively invokes perl (e.g. for 92 Please note that if your callback recursively invokes perl (e.g. for
60 event handlers), then it must be prepared to be called recursively. 93 event handlers), then it must be prepared to be called recursively
94 itself.
61 95
62 STATIC METHODS 96 SIMPLE COROUTINE CREATION
63 Static methods are actually functions that operate on the current
64 coroutine only.
65
66 async { ... } [@args...] 97 async { ... } [@args...]
67 Create a new asynchronous coroutine and return it's coroutine object 98 Create a new coroutine and return it's coroutine object (usually
68 (usually unused). When the sub returns the new coroutine is 99 unused). The coroutine will be put into the ready queue, so it will
100 start running automatically on the next scheduler run.
101
102 The first argument is a codeblock/closure that should be executed in
103 the coroutine. When it returns argument returns the coroutine is
69 automatically terminated. 104 automatically terminated.
70 105
106 The remaining arguments are passed as arguments to the closure.
107
71 See the "Coro::State::new" constructor for info about the coroutine 108 See the "Coro::State::new" constructor for info about the coroutine
72 environment. 109 environment in which coroutines are executed.
73 110
74 Calling "exit" in a coroutine will do the same as calling exit 111 Calling "exit" in a coroutine will do the same as calling exit
75 outside the coroutine. Likewise, when the coroutine dies, the 112 outside the coroutine. Likewise, when the coroutine dies, the
76 program will exit, just as it would in the main program. 113 program will exit, just as it would in the main program.
77 114
115 If you do not want that, you can provide a default "die" handler, or
116 simply avoid dieing (by use of "eval").
117
78 # create a new coroutine that just prints its arguments 118 Example: Create a new coroutine that just prints its arguments.
119
79 async { 120 async {
80 print "@_\n"; 121 print "@_\n";
81 } 1,2,3,4; 122 } 1,2,3,4;
82 123
83 async_pool { ... } [@args...] 124 async_pool { ... } [@args...]
84 Similar to "async", but uses a coroutine pool, so you should not 125 Similar to "async", but uses a coroutine pool, so you should not
85 call terminate or join (although you are allowed to), and you get a 126 call terminate or join on it (although you are allowed to), and you
86 coroutine that might have executed other code already (which can be 127 get a coroutine that might have executed other code already (which
87 good or bad :). 128 can be good or bad :).
88 129
130 On the plus side, this function is faster than creating (and
131 destroying) a completely new coroutine, so if you need a lot of
132 generic coroutines in quick successsion, use "async_pool", not
133 "async".
134
89 Also, the block is executed in an "eval" context and a warning will 135 The code block is executed in an "eval" context and a warning will
90 be issued in case of an exception instead of terminating the 136 be issued in case of an exception instead of terminating the
91 program, as "async" does. As the coroutine is being reused, stuff 137 program, as "async" does. As the coroutine is being reused, stuff
92 like "on_destroy" will not work in the expected way, unless you call 138 like "on_destroy" will not work in the expected way, unless you call
93 terminate or cancel, which somehow defeats the purpose of pooling. 139 terminate or cancel, which somehow defeats the purpose of pooling
140 (but is fine in the exceptional case).
94 141
95 The priority will be reset to 0 after each job, tracing will be 142 The priority will be reset to 0 after each run, tracing will be
96 disabled, the description will be reset and the default output 143 disabled, the description will be reset and the default output
97 filehandle gets restored, so you can change alkl these. Otherwise 144 filehandle gets restored, so you can change all these. Otherwise the
98 the coroutine will be re-used "as-is": most notably if you change 145 coroutine will be re-used "as-is": most notably if you change other
99 other per-coroutine global stuff such as $/ you need to revert that 146 per-coroutine global stuff such as $/ you *must needs* to revert
100 change, which is most simply done by using local as in " local $/ ". 147 that change, which is most simply done by using local as in: " local
148 $/ ".
101 149
102 The pool size is limited to 8 idle coroutines (this can be adjusted 150 The pool size is limited to 8 idle coroutines (this can be adjusted
103 by changing $Coro::POOL_SIZE), and there can be as many non-idle 151 by changing $Coro::POOL_SIZE), and there can be as many non-idle
104 coros as required. 152 coros as required.
105 153
106 If you are concerned about pooled coroutines growing a lot because a 154 If you are concerned about pooled coroutines growing a lot because a
107 single "async_pool" used a lot of stackspace you can e.g. 155 single "async_pool" used a lot of stackspace you can e.g.
108 "async_pool { terminate }" once per second or so to slowly replenish 156 "async_pool { terminate }" once per second or so to slowly replenish
109 the pool. In addition to that, when the stacks used by a handler 157 the pool. In addition to that, when the stacks used by a handler
110 grows larger than 16kb (adjustable with $Coro::POOL_RSS) it will 158 grows larger than 16kb (adjustable via $Coro::POOL_RSS) it will also
111 also exit. 159 be destroyed.
160
161 STATIC METHODS
162 Static methods are actually functions that operate on the current
163 coroutine.
112 164
113 schedule 165 schedule
114 Calls the scheduler. Please note that the current coroutine will not 166 Calls the scheduler. The scheduler will find the next coroutine that
167 is to be run from the ready queue and switches to it. The next
168 coroutine to be run is simply the one with the highest priority that
169 is longest in its ready queue. If there is no coroutine ready, it
170 will clal the $Coro::idle hook.
171
172 Please note that the current coroutine will *not* be put into the
115 be put into the ready queue, so calling this function usually means 173 ready queue, so calling this function usually means you will never
116 you will never be called again unless something else (e.g. an event 174 be called again unless something else (e.g. an event handler) calls
117 handler) calls ready. 175 "->ready", thus waking you up.
176
177 This makes "schedule" *the* generic method to use to block the
178 current coroutine and wait for events: first you remember the
179 current coroutine in a variable, then arrange for some callback of
180 yours to call "->ready" on that once some event happens, and last
181 you call "schedule" to put yourself to sleep. Note that a lot of
182 things can wake your coroutine up, so you need to check wether the
183 event indeed happened, e.g. by storing the status in a variable.
118 184
119 The canonical way to wait on external events is this: 185 The canonical way to wait on external events is this:
120 186
121 { 187 {
122 # remember current coroutine 188 # remember current coroutine
137 203
138 cede 204 cede
139 "Cede" to other coroutines. This function puts the current coroutine 205 "Cede" to other coroutines. This function puts the current coroutine
140 into the ready queue and calls "schedule", which has the effect of 206 into the ready queue and calls "schedule", which has the effect of
141 giving up the current "timeslice" to other coroutines of the same or 207 giving up the current "timeslice" to other coroutines of the same or
142 higher priority. 208 higher priority. Once your coroutine gets its turn again it will
209 automatically be resumed.
143 210
144 Returns true if at least one coroutine switch has happened. 211 This function is often called "yield" in other languages.
145 212
146 Coro::cede_notself 213 Coro::cede_notself
147 Works like cede, but is not exported by default and will cede to any 214 Works like cede, but is not exported by default and will cede to
148 coroutine, regardless of priority, once. 215 *any* coroutine, regardless of priority. This is useful sometimes to
149 216 ensure progress is made.
150 Returns true if at least one coroutine switch has happened.
151 217
152 terminate [arg...] 218 terminate [arg...]
153 Terminates the current coroutine with the given status values (see 219 Terminates the current coroutine with the given status values (see
154 cancel). 220 cancel).
155 221
156 killall 222 killall
157 Kills/terminates/cancels all coroutines except the currently running 223 Kills/terminates/cancels all coroutines except the currently running
158 one. This is useful after a fork, either in the child or the parent, 224 one. This is useful after a fork, either in the child or the parent,
159 as usually only one of them should inherit the running coroutines. 225 as usually only one of them should inherit the running coroutines.
160 226
161 # dynamic methods 227 Note that while this will try to free some of the main programs
228 resources, you cnanot free all of them, so if a coroutine that is
229 not the main program calls this function, there will be some
230 one-time resource leak.
162 231
163 COROUTINE METHODS 232 COROUTINE METHODS
164 These are the methods you can call on coroutine objects. 233 These are the methods you can call on coroutine objects (or to create
234 them).
165 235
166 new Coro \&sub [, @args...] 236 new Coro \&sub [, @args...]
167 Create a new coroutine and return it. When the sub returns the 237 Create a new coroutine and return it. When the sub returns, the
168 coroutine automatically terminates as if "terminate" with the 238 coroutine automatically terminates as if "terminate" with the
169 returned values were called. To make the coroutine run you must 239 returned values were called. To make the coroutine run you must
170 first put it into the ready queue by calling the ready method. 240 first put it into the ready queue by calling the ready method.
171 241
172 See "async" and "Coro::State::new" for additional info about the 242 See "async" and "Coro::State::new" for additional info about the
173 coroutine environment. 243 coroutine environment.
174 244
175 $success = $coroutine->ready 245 $success = $coroutine->ready
176 Put the given coroutine into the ready queue (according to it's 246 Put the given coroutine into the end of its ready queue (there is
177 priority) and return true. If the coroutine is already in the ready 247 one queue for each priority) and return true. If the coroutine is
178 queue, do nothing and return false. 248 already in the ready queue, do nothing and return false.
249
250 This ensures that the scheduler will resume this coroutine
251 automatically once all the coroutines of higher priority and all
252 coroutines of the same priority that were put into the ready queue
253 earlier have been resumed.
179 254
180 $is_ready = $coroutine->is_ready 255 $is_ready = $coroutine->is_ready
181 Return wether the coroutine is currently the ready queue or not, 256 Return wether the coroutine is currently the ready queue or not,
182 257
183 $coroutine->cancel (arg...) 258 $coroutine->cancel (arg...)
186 coroutine is the current coroutine. 261 coroutine is the current coroutine.
187 262
188 $coroutine->join 263 $coroutine->join
189 Wait until the coroutine terminates and return any values given to 264 Wait until the coroutine terminates and return any values given to
190 the "terminate" or "cancel" functions. "join" can be called 265 the "terminate" or "cancel" functions. "join" can be called
191 concurrently from multiple coroutines. 266 concurrently from multiple coroutines, and all will be resumed and
267 given the status return once the $coroutine terminates.
192 268
193 $coroutine->on_destroy (\&cb) 269 $coroutine->on_destroy (\&cb)
194 Registers a callback that is called when this coroutine gets 270 Registers a callback that is called when this coroutine gets
195 destroyed, but before it is joined. The callback gets passed the 271 destroyed, but before it is joined. The callback gets passed the
196 terminate arguments, if any. 272 terminate arguments, if any, and *must not* die, under any
273 circumstances.
197 274
198 $oldprio = $coroutine->prio ($newprio) 275 $oldprio = $coroutine->prio ($newprio)
199 Sets (or gets, if the argument is missing) the priority of the 276 Sets (or gets, if the argument is missing) the priority of the
200 coroutine. Higher priority coroutines get run before lower priority 277 coroutine. Higher priority coroutines get run before lower priority
201 coroutines. Priorities are small signed integers (currently -4 .. 278 coroutines. Priorities are small signed integers (currently -4 ..
245 well end the whole program. 322 well end the whole program.
246 323
247 GLOBAL FUNCTIONS 324 GLOBAL FUNCTIONS
248 Coro::nready 325 Coro::nready
249 Returns the number of coroutines that are currently in the ready 326 Returns the number of coroutines that are currently in the ready
250 state, i.e. that can be switched to. The value 0 means that the only 327 state, i.e. that can be switched to by calling "schedule" directory
251 runnable coroutine is the currently running one, so "cede" would 328 or indirectly. The value 0 means that the only runnable coroutine is
252 have no effect, and "schedule" would cause a deadlock unless there 329 the currently running one, so "cede" would have no effect, and
330 "schedule" would cause a deadlock unless there is an idle handler
253 is an idle handler that wakes up some coroutines. 331 that wakes up some coroutines.
254 332
255 my $guard = Coro::guard { ... } 333 my $guard = Coro::guard { ... }
256 This creates and returns a guard object. Nothing happens until the 334 This creates and returns a guard object. Nothing happens until the
257 object gets destroyed, in which case the codeblock given as argument 335 object gets destroyed, in which case the codeblock given as argument
258 will be executed. This is useful to free locks or other resources in 336 will be executed. This is useful to free locks or other resources in
271 # do something that requires $busy to be true 349 # do something that requires $busy to be true
272 } 350 }
273 351
274 unblock_sub { ... } 352 unblock_sub { ... }
275 This utility function takes a BLOCK or code reference and "unblocks" 353 This utility function takes a BLOCK or code reference and "unblocks"
276 it, returning the new coderef. This means that the new coderef will 354 it, returning a new coderef. Unblocking means that calling the new
277 return immediately without blocking, returning nothing, while the 355 coderef will return immediately without blocking, returning nothing,
278 original code ref will be called (with parameters) from within its 356 while the original code ref will be called (with parameters) from
279 own coroutine. 357 within another coroutine.
280 358
281 The reason this function exists is that many event libraries (such 359 The reason this function exists is that many event libraries (such
282 as the venerable Event module) are not coroutine-safe (a weaker form 360 as the venerable Event module) are not coroutine-safe (a weaker form
283 of thread-safety). This means you must not block within event 361 of thread-safety). This means you must not block within event
284 callbacks, otherwise you might suffer from crashes or worse. 362 callbacks, otherwise you might suffer from crashes or worse. The
363 only event library currently known that is safe to use without
364 "unblock_sub" is EV.
285 365
286 This function allows your callbacks to block by executing them in 366 This function allows your callbacks to block by executing them in
287 another coroutine where it is safe to block. One example where 367 another coroutine where it is safe to block. One example where
288 blocking is handy is when you use the Coro::AIO functions to save 368 blocking is handy is when you use the Coro::AIO functions to save
289 results to disk. 369 results to disk, for example.
290 370
291 In short: simply use "unblock_sub { ... }" instead of "sub { ... }" 371 In short: simply use "unblock_sub { ... }" instead of "sub { ... }"
292 when creating event callbacks that want to block. 372 when creating event callbacks that want to block.
293 373
374 If your handler does not plan to block (e.g. simply sends a message
375 to another coroutine, or puts some other coroutine into the ready
376 queue), there is no reason to use "unblock_sub".
377
378 Note that you also need to use "unblock_sub" for any other callbacks
379 that are indirectly executed by any C-based event loop. For example,
380 when you use a module that uses AnyEvent (and you use
381 Coro::AnyEvent) and it provides callbacks that are the result of
382 some event callback, then you must not block either, or use
383 "unblock_sub".
384
294BUGS/LIMITATIONS 385BUGS/LIMITATIONS
295 - you must make very sure that no coro is still active on global
296 destruction. very bad things might happen otherwise (usually segfaults).
297
298 - this module is not thread-safe. You should only ever use this module 386 This module is not perl-pseudo-thread-safe. You should only ever use
299 from the same thread (this requirement might be loosened in the future 387 this module from the same thread (this requirement might be removed in
300 to allow per-thread schedulers, but Coro::State does not yet allow 388 the future to allow per-thread schedulers, but Coro::State does not yet
301 this). 389 allow this). I recommend disabling thread support and using processes,
390 as this is much faster and uses less memory.
302 391
303SEE ALSO 392SEE ALSO
393 Event-Loop integration: Coro::AnyEvent, Coro::EV, Coro::Event.
394
395 Debugging: Coro::Debug.
396
304 Support/Utility: Coro::Specific, Coro::State, Coro::Util. 397 Support/Utility: Coro::Specific, Coro::Util.
305 398
306 Locking/IPC: Coro::Signal, Coro::Channel, Coro::Semaphore, 399 Locking/IPC: Coro::Signal, Coro::Channel, Coro::Semaphore,
307 Coro::SemaphoreSet, Coro::RWLock. 400 Coro::SemaphoreSet, Coro::RWLock.
308 401
309 Event/IO: Coro::Timer, Coro::Event, Coro::Handle, Coro::Socket, 402 IO/Timers: Coro::Timer, Coro::Handle, Coro::Socket, Coro::AIO.
310 Coro::Select.
311 403
312 Embedding: <Coro:MakeMaker> 404 Compatibility: Coro::LWP, Coro::BDB, Coro::Storable, Coro::Select.
405
406 XS API: Coro::MakeMaker.
407
408 Low level Configuration, Coroutine Environment: Coro::State.
313 409
314AUTHOR 410AUTHOR
315 Marc Lehmann <schmorp@schmorp.de> 411 Marc Lehmann <schmorp@schmorp.de>
316 http://home.schmorp.de/ 412 http://home.schmorp.de/
317 413

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines