… | |
… | |
6 | |
6 | |
7 | async { |
7 | async { |
8 | # some asynchronous thread of execution |
8 | # some asynchronous thread of execution |
9 | }; |
9 | }; |
10 | |
10 | |
11 | # alternatively create an async process like this: |
11 | # alternatively create an async coroutine like this: |
12 | |
12 | |
13 | sub some_func : Coro { |
13 | sub some_func : Coro { |
14 | # some more async code |
14 | # some more async code |
15 | } |
15 | } |
16 | |
16 | |
17 | cede; |
17 | cede; |
18 | |
18 | |
19 | DESCRIPTION |
19 | DESCRIPTION |
20 | This module collection manages coroutines. Coroutines are similar to |
20 | This module collection manages coroutines. Coroutines are similar to |
21 | threads but don't run in parallel. |
21 | threads but don't run in parallel at the same time even on SMP machines. |
|
|
22 | The specific flavor of coroutine used in this module also guarantees you |
|
|
23 | that it will not switch between coroutines unless necessary, at |
|
|
24 | easily-identified points in your program, so locking and parallel access |
|
|
25 | are rarely an issue, making coroutine programming much safer than |
|
|
26 | threads programming. |
|
|
27 | |
|
|
28 | (Perl, however, does not natively support real threads but instead does |
|
|
29 | a very slow and memory-intensive emulation of processes using threads. |
|
|
30 | This is a performance win on Windows machines, and a loss everywhere |
|
|
31 | else). |
22 | |
32 | |
23 | In this module, coroutines are defined as "callchain + lexical variables |
33 | In this module, coroutines are defined as "callchain + lexical variables |
24 | + @_ + $_ + $@ + $^W + C stack), that is, a coroutine has it's own |
34 | + @_ + $_ + $@ + $/ + C stack), that is, a coroutine has its own |
25 | callchain, it's own set of lexicals and it's own set of perl's most |
35 | callchain, its own set of lexicals and its own set of perls most |
26 | important global variables. |
36 | important global variables. |
27 | |
37 | |
28 | $main |
38 | $main |
29 | This coroutine represents the main program. |
39 | This coroutine represents the main program. |
30 | |
40 | |
31 | $current (or as function: current) |
41 | $current (or as function: current) |
32 | The current coroutine (the last coroutine switched to). The initial |
42 | The current coroutine (the last coroutine switched to). The initial |
33 | value is $main (of course). |
43 | value is $main (of course). |
34 | |
44 | |
|
|
45 | This variable is strictly *read-only*. It is provided for |
|
|
46 | performance reasons. If performance is not essential you are |
|
|
47 | encouraged to use the "Coro::current" function instead. |
|
|
48 | |
35 | $idle |
49 | $idle |
36 | The coroutine to switch to when no other coroutine is running. The |
50 | A callback that is called whenever the scheduler finds no ready |
37 | default implementation prints "FATAL: deadlock detected" and exits. |
51 | coroutines to run. The default implementation prints "FATAL: |
|
|
52 | deadlock detected" and exits, because the program has no other way |
|
|
53 | to continue. |
|
|
54 | |
|
|
55 | 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 |
|
|
57 | coroutine so the scheduler can run it. |
|
|
58 | |
|
|
59 | Please note that if your callback recursively invokes perl (e.g. for |
|
|
60 | event handlers), then it must be prepared to be called recursively. |
38 | |
61 | |
39 | STATIC METHODS |
62 | STATIC METHODS |
40 | Static methods are actually functions that operate on the current |
63 | Static methods are actually functions that operate on the current |
41 | process only. |
64 | coroutine only. |
42 | |
65 | |
43 | async { ... } [@args...] |
66 | async { ... } [@args...] |
44 | Create a new asynchronous process and return it's process object |
67 | Create a new asynchronous coroutine and return it's coroutine object |
45 | (usually unused). When the sub returns the new process is |
68 | (usually unused). When the sub returns the new coroutine is |
46 | automatically terminated. |
69 | automatically terminated. |
47 | |
70 | |
48 | When the coroutine dies, the program will exit, just as in the main |
71 | See the "Coro::State::new" constructor for info about the coroutine |
49 | program. |
72 | environment. |
|
|
73 | |
|
|
74 | Calling "exit" in a coroutine will do the same as calling exit |
|
|
75 | outside the coroutine. Likewise, when the coroutine dies, the |
|
|
76 | program will exit, just as it would in the main program. |
50 | |
77 | |
51 | # create a new coroutine that just prints its arguments |
78 | # create a new coroutine that just prints its arguments |
52 | async { |
79 | async { |
53 | print "@_\n"; |
80 | print "@_\n"; |
54 | } 1,2,3,4; |
81 | } 1,2,3,4; |
55 | |
82 | |
|
|
83 | async_pool { ... } [@args...] |
|
|
84 | 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 |
|
|
86 | coroutine that might have executed other code already (which can be |
|
|
87 | good or bad :). |
|
|
88 | |
|
|
89 | Also, the block is executed in an "eval" context and a warning will |
|
|
90 | be issued in case of an exception instead of terminating the |
|
|
91 | 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 |
|
|
93 | terminate or cancel, which somehow defeats the purpose of pooling. |
|
|
94 | |
|
|
95 | The priority will be reset to 0 after each job, tracing will be |
|
|
96 | disabled, the description will be reset and the default output |
|
|
97 | filehandle gets restored, so you can change alkl these. Otherwise |
|
|
98 | the coroutine will be re-used "as-is": most notably if you change |
|
|
99 | other per-coroutine global stuff such as $/ you need to revert that |
|
|
100 | change, which is most simply done by using local as in " local $/ ". |
|
|
101 | |
|
|
102 | 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 |
|
|
104 | coros as required. |
|
|
105 | |
|
|
106 | 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. |
|
|
108 | "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 |
|
|
110 | grows larger than 16kb (adjustable with $Coro::POOL_RSS) it will |
|
|
111 | also exit. |
|
|
112 | |
56 | schedule |
113 | schedule |
57 | Calls the scheduler. Please note that the current process will not |
114 | Calls the scheduler. Please note that the current coroutine will not |
58 | be put into the ready queue, so calling this function usually means |
115 | be put into the ready queue, so calling this function usually means |
59 | you will never be called again. |
116 | you will never be called again unless something else (e.g. an event |
|
|
117 | handler) calls ready. |
|
|
118 | |
|
|
119 | The canonical way to wait on external events is this: |
|
|
120 | |
|
|
121 | { |
|
|
122 | # remember current coroutine |
|
|
123 | my $current = $Coro::current; |
|
|
124 | |
|
|
125 | # register a hypothetical event handler |
|
|
126 | on_event_invoke sub { |
|
|
127 | # wake up sleeping coroutine |
|
|
128 | $current->ready; |
|
|
129 | undef $current; |
|
|
130 | }; |
|
|
131 | |
|
|
132 | # call schedule until event occurred. |
|
|
133 | # in case we are woken up for other reasons |
|
|
134 | # (current still defined), loop. |
|
|
135 | Coro::schedule while $current; |
|
|
136 | } |
60 | |
137 | |
61 | cede |
138 | cede |
62 | "Cede" to other processes. This function puts the current process |
139 | "Cede" to other coroutines. This function puts the current coroutine |
63 | into the ready queue and calls "schedule", which has the effect of |
140 | into the ready queue and calls "schedule", which has the effect of |
64 | giving up the current "timeslice" to other coroutines of the same or |
141 | giving up the current "timeslice" to other coroutines of the same or |
65 | higher priority. |
142 | higher priority. |
66 | |
143 | |
|
|
144 | Returns true if at least one coroutine switch has happened. |
|
|
145 | |
|
|
146 | Coro::cede_notself |
|
|
147 | Works like cede, but is not exported by default and will cede to any |
|
|
148 | coroutine, regardless of priority, once. |
|
|
149 | |
|
|
150 | Returns true if at least one coroutine switch has happened. |
|
|
151 | |
67 | terminate [arg...] |
152 | terminate [arg...] |
68 | Terminates the current process with the given status values (see |
153 | Terminates the current coroutine with the given status values (see |
69 | cancel). |
154 | cancel). |
70 | |
155 | |
|
|
156 | killall |
|
|
157 | Kills/terminates/cancels all coroutines except the currently running |
|
|
158 | 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. |
|
|
160 | |
71 | # dynamic methods |
161 | # dynamic methods |
72 | |
162 | |
73 | PROCESS METHODS |
163 | COROUTINE METHODS |
74 | These are the methods you can call on process objects. |
164 | These are the methods you can call on coroutine objects. |
75 | |
165 | |
76 | new Coro \&sub [, @args...] |
166 | new Coro \&sub [, @args...] |
77 | Create a new process and return it. When the sub returns the process |
167 | Create a new coroutine and return it. When the sub returns the |
78 | automatically terminates as if "terminate" with the returned values |
168 | coroutine automatically terminates as if "terminate" with the |
79 | were called. To make the process run you must first put it into the |
169 | returned values were called. To make the coroutine run you must |
80 | ready queue by calling the ready method. |
170 | first put it into the ready queue by calling the ready method. |
81 | |
171 | |
82 | $process->ready |
172 | See "async" and "Coro::State::new" for additional info about the |
|
|
173 | coroutine environment. |
|
|
174 | |
|
|
175 | $success = $coroutine->ready |
83 | Put the given process into the ready queue. |
176 | Put the given coroutine into the ready queue (according to it's |
|
|
177 | priority) and return true. If the coroutine is already in the ready |
|
|
178 | queue, do nothing and return false. |
84 | |
179 | |
|
|
180 | $is_ready = $coroutine->is_ready |
|
|
181 | Return wether the coroutine is currently the ready queue or not, |
|
|
182 | |
85 | $process->cancel (arg...) |
183 | $coroutine->cancel (arg...) |
86 | Terminates the given process and makes it return the given arguments |
184 | Terminates the given coroutine and makes it return the given |
87 | as status (default: the empty list). |
185 | arguments as status (default: the empty list). Never returns if the |
|
|
186 | coroutine is the current coroutine. |
88 | |
187 | |
89 | $process->join |
188 | $coroutine->join |
90 | Wait until the coroutine terminates and return any values given to |
189 | Wait until the coroutine terminates and return any values given to |
91 | the "terminate" or "cancel" functions. "join" can be called multiple |
190 | the "terminate" or "cancel" functions. "join" can be called |
92 | times from multiple processes. |
191 | concurrently from multiple coroutines. |
93 | |
192 | |
|
|
193 | $coroutine->on_destroy (\&cb) |
|
|
194 | Registers a callback that is called when this coroutine gets |
|
|
195 | destroyed, but before it is joined. The callback gets passed the |
|
|
196 | terminate arguments, if any. |
|
|
197 | |
94 | $oldprio = $process->prio($newprio) |
198 | $oldprio = $coroutine->prio ($newprio) |
95 | Sets (or gets, if the argument is missing) the priority of the |
199 | Sets (or gets, if the argument is missing) the priority of the |
96 | process. Higher priority processes get run before lower priority |
200 | coroutine. Higher priority coroutines get run before lower priority |
97 | processes. Priorities are small signed integers (currently -4 .. |
201 | coroutines. Priorities are small signed integers (currently -4 .. |
98 | +3), that you can refer to using PRIO_xxx constants (use the import |
202 | +3), that you can refer to using PRIO_xxx constants (use the import |
99 | tag :prio to get then): |
203 | tag :prio to get then): |
100 | |
204 | |
101 | PRIO_MAX > PRIO_HIGH > PRIO_NORMAL > PRIO_LOW > PRIO_IDLE > PRIO_MIN |
205 | PRIO_MAX > PRIO_HIGH > PRIO_NORMAL > PRIO_LOW > PRIO_IDLE > PRIO_MIN |
102 | 3 > 1 > 0 > -1 > -3 > -4 |
206 | 3 > 1 > 0 > -1 > -3 > -4 |
… | |
… | |
105 | current->prio(PRIO_HIGH); |
209 | current->prio(PRIO_HIGH); |
106 | |
210 | |
107 | The idle coroutine ($Coro::idle) always has a lower priority than |
211 | The idle coroutine ($Coro::idle) always has a lower priority than |
108 | any existing coroutine. |
212 | any existing coroutine. |
109 | |
213 | |
110 | Changing the priority of the current process will take effect |
214 | Changing the priority of the current coroutine will take effect |
111 | immediately, but changing the priority of processes in the ready |
215 | immediately, but changing the priority of coroutines in the ready |
112 | queue (but not running) will only take effect after the next |
216 | queue (but not running) will only take effect after the next |
113 | schedule (of that process). This is a bug that will be fixed in some |
217 | schedule (of that coroutine). This is a bug that will be fixed in |
114 | future version. |
218 | some future version. |
115 | |
219 | |
116 | $newprio = $process->nice($change) |
220 | $newprio = $coroutine->nice ($change) |
117 | Similar to "prio", but subtract the given value from the priority |
221 | Similar to "prio", but subtract the given value from the priority |
118 | (i.e. higher values mean lower priority, just as in unix). |
222 | (i.e. higher values mean lower priority, just as in unix). |
119 | |
223 | |
120 | $olddesc = $process->desc($newdesc) |
224 | $olddesc = $coroutine->desc ($newdesc) |
121 | Sets (or gets in case the argument is missing) the description for |
225 | Sets (or gets in case the argument is missing) the description for |
122 | this process. This is just a free-form string you can associate with |
226 | this coroutine. This is just a free-form string you can associate |
123 | a process. |
227 | with a coroutine. |
|
|
228 | |
|
|
229 | This method simply sets the "$coroutine->{desc}" member to the given |
|
|
230 | string. You can modify this member directly if you wish. |
|
|
231 | |
|
|
232 | $coroutine->throw ([$scalar]) |
|
|
233 | If $throw is specified and defined, it will be thrown as an |
|
|
234 | exception inside the coroutine at the next convinient point in time |
|
|
235 | (usually after it gains control at the next schedule/transfer/cede). |
|
|
236 | Otherwise clears the exception object. |
|
|
237 | |
|
|
238 | The exception object will be thrown "as is" with the specified |
|
|
239 | scalar in $@, i.e. if it is a string, no line number or newline will |
|
|
240 | be appended (unlike with "die"). |
|
|
241 | |
|
|
242 | This can be used as a softer means than "cancel" to ask a coroutine |
|
|
243 | to end itself, although there is no guarentee that the exception |
|
|
244 | will lead to termination, and if the exception isn't caught it might |
|
|
245 | well end the whole program. |
|
|
246 | |
|
|
247 | GLOBAL FUNCTIONS |
|
|
248 | Coro::nready |
|
|
249 | 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 |
|
|
251 | runnable coroutine is the currently running one, so "cede" would |
|
|
252 | have no effect, and "schedule" would cause a deadlock unless there |
|
|
253 | is an idle handler that wakes up some coroutines. |
|
|
254 | |
|
|
255 | my $guard = Coro::guard { ... } |
|
|
256 | This creates and returns a guard object. Nothing happens until the |
|
|
257 | 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 |
|
|
259 | case of a runtime error or when the coroutine gets canceled, as in |
|
|
260 | both cases the guard block will be executed. The guard object |
|
|
261 | supports only one method, "->cancel", which will keep the codeblock |
|
|
262 | from being executed. |
|
|
263 | |
|
|
264 | Example: set some flag and clear it again when the coroutine gets |
|
|
265 | canceled or the function returns: |
|
|
266 | |
|
|
267 | sub do_something { |
|
|
268 | my $guard = Coro::guard { $busy = 0 }; |
|
|
269 | $busy = 1; |
|
|
270 | |
|
|
271 | # do something that requires $busy to be true |
|
|
272 | } |
|
|
273 | |
|
|
274 | unblock_sub { ... } |
|
|
275 | This utility function takes a BLOCK or code reference and "unblocks" |
|
|
276 | it, returning the new coderef. This means that the new coderef will |
|
|
277 | return immediately without blocking, returning nothing, while the |
|
|
278 | original code ref will be called (with parameters) from within its |
|
|
279 | own coroutine. |
|
|
280 | |
|
|
281 | The reason this function exists is that many event libraries (such |
|
|
282 | as the venerable Event module) are not coroutine-safe (a weaker form |
|
|
283 | of thread-safety). This means you must not block within event |
|
|
284 | callbacks, otherwise you might suffer from crashes or worse. |
|
|
285 | |
|
|
286 | This function allows your callbacks to block by executing them in |
|
|
287 | 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 |
|
|
289 | results to disk. |
|
|
290 | |
|
|
291 | In short: simply use "unblock_sub { ... }" instead of "sub { ... }" |
|
|
292 | when creating event callbacks that want to block. |
124 | |
293 | |
125 | BUGS/LIMITATIONS |
294 | BUGS/LIMITATIONS |
126 | - you must make very sure that no coro is still active on global |
295 | - you must make very sure that no coro is still active on global |
127 | destruction. very bad things might happen otherwise (usually segfaults). |
296 | destruction. very bad things might happen otherwise (usually segfaults). |
128 | |
297 | |
129 | - this module is not thread-safe. You should only ever use this module |
298 | - this module is not thread-safe. You should only ever use this module |
130 | from the same thread (this requirement might be losened in the future |
299 | from the same thread (this requirement might be loosened in the future |
131 | to allow per-thread schedulers, but Coro::State does not yet allow |
300 | to allow per-thread schedulers, but Coro::State does not yet allow |
132 | this). |
301 | this). |
133 | |
302 | |
134 | SEE ALSO |
303 | SEE ALSO |
135 | Support/Utility: Coro::Cont, Coro::Specific, Coro::State, Coro::Util. |
304 | Support/Utility: Coro::Specific, Coro::State, Coro::Util. |
136 | |
305 | |
137 | Locking/IPC: Coro::Signal, Coro::Channel, Coro::Semaphore, |
306 | Locking/IPC: Coro::Signal, Coro::Channel, Coro::Semaphore, |
138 | Coro::SemaphoreSet, Coro::RWLock. |
307 | Coro::SemaphoreSet, Coro::RWLock. |
139 | |
308 | |
140 | Event/IO: Coro::Timer, Coro::Event, Coro::Handle, Coro::Socket, |
309 | Event/IO: Coro::Timer, Coro::Event, Coro::Handle, Coro::Socket, |