1AIO(3)                User Contributed Perl Documentation               AIO(3)
2
3
4

NAME

6       IO::AIO - Asynchronous Input/Output
7

SYNOPSIS

9        use IO::AIO;
10
11        aio_open "/etc/passwd", O_RDONLY, 0, sub {
12           my $fh = shift
13              or die "/etc/passwd: $!";
14           ...
15        };
16
17        aio_unlink "/tmp/file", sub { };
18
19        aio_read $fh, 30000, 1024, $buffer, 0, sub {
20           $_[0] > 0 or die "read error: $!";
21        };
22
23        # version 2+ has request and group objects
24        use IO::AIO 2;
25
26        aioreq_pri 4; # give next request a very high priority
27        my $req = aio_unlink "/tmp/file", sub { };
28        $req->cancel; # cancel request if still in queue
29
30        my $grp = aio_group sub { print "all stats done\n" };
31        add $grp aio_stat "..." for ...;
32
33        # AnyEvent integration
34        open my $fh, "<&=" . IO::AIO::poll_fileno or die "$!";
35        my $w = AnyEvent->io (fh => $fh, poll => 'r', cb => sub { IO::AIO::poll_cb });
36
37        # Event integration
38        Event->io (fd => IO::AIO::poll_fileno,
39                   poll => 'r',
40                   cb => \&IO::AIO::poll_cb);
41
42        # Glib/Gtk2 integration
43        add_watch Glib::IO IO::AIO::poll_fileno,
44                  in => sub { IO::AIO::poll_cb; 1 };
45
46        # Tk integration
47        Tk::Event::IO->fileevent (IO::AIO::poll_fileno, "",
48                                  readable => \&IO::AIO::poll_cb);
49
50        # Danga::Socket integration
51        Danga::Socket->AddOtherFds (IO::AIO::poll_fileno =>
52                                    \&IO::AIO::poll_cb);
53

DESCRIPTION

55       This module implements asynchronous I/O using whatever means your oper‐
56       ating system supports.
57
58       Asynchronous means that operations that can normally block your program
59       (e.g. reading from disk) will be done asynchronously: the operation
60       will still block, but you can do something else in the meantime. This
61       is extremely useful for programs that need to stay interactive even
62       when doing heavy I/O (GUI programs, high performance network servers
63       etc.), but can also be used to easily do operations in parallel that
64       are normally done sequentially, e.g. stat'ing many files, which is much
65       faster on a RAID volume or over NFS when you do a number of stat opera‐
66       tions concurrently.
67
68       While most of this works on all types of file descriptors (for example
69       sockets), using these functions on file descriptors that support non‐
70       blocking operation (again, sockets, pipes etc.) is very inefficient or
71       might not work (aio_read fails on sockets/pipes/fifos). Use an event
72       loop for that (such as the Event module): IO::AIO will naturally fit
73       into such an event loop itself.
74
75       In this version, a number of threads are started that execute your
76       requests and signal their completion. You don't need thread support in
77       perl, and the threads created by this module will not be visible to
78       perl. In the future, this module might make use of the native aio func‐
79       tions available on many operating systems. However, they are often not
80       well-supported or restricted (GNU/Linux doesn't allow them on normal
81       files currently, for example), and they would only support aio_read and
82       aio_write, so the remaining functionality would have to be implemented
83       using threads anyway.
84
85       Although the module will work with in the presence of other (Perl-)
86       threads, it is currently not reentrant in any way, so use appropriate
87       locking yourself, always call "poll_cb" from within the same thread, or
88       never call "poll_cb" (or other "aio_" functions) recursively.
89
90       EXAMPLE
91
92       This is a simple example that uses the Event module and loads
93       /etc/passwd asynchronously:
94
95          use Fcntl;
96          use Event;
97          use IO::AIO;
98
99          # register the IO::AIO callback with Event
100          Event->io (fd => IO::AIO::poll_fileno,
101                     poll => 'r',
102                     cb => \&IO::AIO::poll_cb);
103
104          # queue the request to open /etc/passwd
105          aio_open "/etc/passwd", O_RDONLY, 0, sub {
106             my $fh = shift
107                or die "error while opening: $!";
108
109             # stat'ing filehandles is generally non-blocking
110             my $size = -s $fh;
111
112             # queue a request to read the file
113             my $contents;
114             aio_read $fh, 0, $size, $contents, 0, sub {
115                $_[0] == $size
116                   or die "short read: $!";
117
118                close $fh;
119
120                # file contents now in $contents
121                print $contents;
122
123                # exit event loop and program
124                Event::unloop;
125             };
126          };
127
128          # possibly queue up other requests, or open GUI windows,
129          # check for sockets etc. etc.
130
131          # process events as long as there are some:
132          Event::loop;
133

REQUEST ANATOMY AND LIFETIME

135       Every "aio_*" function creates a request. which is a C data structure
136       not directly visible to Perl.
137
138       If called in non-void context, every request function returns a Perl
139       object representing the request. In void context, nothing is returned,
140       which saves a bit of memory.
141
142       The perl object is a fairly standard ref-to-hash object. The hash con‐
143       tents are not used by IO::AIO so you are free to store anything you
144       like in it.
145
146       During their existance, aio requests travel through the following
147       states, in order:
148
149       ready
150           Immediately after a request is created it is put into the ready
151           state, waiting for a thread to execute it.
152
153       execute
154           A thread has accepted the request for processing and is currently
155           executing it (e.g. blocking in read).
156
157       pending
158           The request has been executed and is waiting for result processing.
159
160           While request submission and execution is fully asynchronous,
161           result processing is not and relies on the perl interpreter calling
162           "poll_cb" (or another function with the same effect).
163
164       result
165           The request results are processed synchronously by "poll_cb".
166
167           The "poll_cb" function will process all outstanding aio requests by
168           calling their callbacks, freeing memory associated with them and
169           managing any groups they are contained in.
170
171       done
172           Request has reached the end of its lifetime and holds no resources
173           anymore (except possibly for the Perl object, but its connection to
174           the actual aio request is severed and calling its methods will
175           either do nothing or result in a runtime error).
176

FUNCTIONS

178       AIO REQUEST FUNCTIONS
179
180       All the "aio_*" calls are more or less thin wrappers around the syscall
181       with the same name (sans "aio_"). The arguments are similar or identi‐
182       cal, and they all accept an additional (and optional) $callback argu‐
183       ment which must be a code reference. This code reference will get
184       called with the syscall return code (e.g. most syscalls return "-1" on
185       error, unlike perl, which usually delivers "false") as it's sole argu‐
186       ment when the given syscall has been executed asynchronously.
187
188       All functions expecting a filehandle keep a copy of the filehandle
189       internally until the request has finished.
190
191       All functions return request objects of type IO::AIO::REQ that allow
192       further manipulation of those requests while they are in-flight.
193
194       The pathnames you pass to these routines must be absolute and encoded
195       as octets. The reason for the former is that at the time the request is
196       being executed, the current working directory could have changed.
197       Alternatively, you can make sure that you never change the current
198       working directory anywhere in the program and then use relative paths.
199
200       To encode pathnames as octets, either make sure you either: a) always
201       pass in filenames you got from outside (command line, readdir etc.)
202       without tinkering, b) are ASCII or ISO 8859-1, c) use the Encode module
203       and encode your pathnames to the locale (or other) encoding in effect
204       in the user environment, d) use Glib::filename_from_unicode on unicode
205       filenames or e) use something else to ensure your scalar has the cor‐
206       rect contents.
207
208       This works, btw. independent of the internal UTF-8 bit, which IO::AIO
209       handles correctly wether it is set or not.
210
211       $prev_pri = aioreq_pri [$pri]
212           Returns the priority value that would be used for the next request
213           and, if $pri is given, sets the priority for the next aio request.
214
215           The default priority is 0, the minimum and maximum priorities are
216           "-4" and 4, respectively. Requests with higher priority will be
217           serviced first.
218
219           The priority will be reset to 0 after each call to one of the
220           "aio_*" functions.
221
222           Example: open a file with low priority, then read something from it
223           with higher priority so the read request is serviced before other
224           low priority open requests (potentially spamming the cache):
225
226              aioreq_pri -3;
227              aio_open ..., sub {
228                 return unless $_[0];
229
230                 aioreq_pri -2;
231                 aio_read $_[0], ..., sub {
232                    ...
233                 };
234              };
235
236       aioreq_nice $pri_adjust
237           Similar to "aioreq_pri", but subtracts the given value from the
238           current priority, so the effect is cumulative.
239
240       aio_open $pathname, $flags, $mode, $callback->($fh)
241           Asynchronously open or create a file and call the callback with a
242           newly created filehandle for the file.
243
244           The pathname passed to "aio_open" must be absolute. See API NOTES,
245           above, for an explanation.
246
247           The $flags argument is a bitmask. See the "Fcntl" module for a
248           list. They are the same as used by "sysopen".
249
250           Likewise, $mode specifies the mode of the newly created file, if it
251           didn't exist and "O_CREAT" has been given, just like perl's
252           "sysopen", except that it is mandatory (i.e. use 0 if you don't
253           create new files, and 0666 or 0777 if you do). Note that the $mode
254           will be modified by the umask in effect then the request is being
255           executed, so better never change the umask.
256
257           Example:
258
259              aio_open "/etc/passwd", O_RDONLY, 0, sub {
260                 if ($_[0]) {
261                    print "open successful, fh is $_[0]\n";
262                    ...
263                 } else {
264                    die "open failed: $!\n";
265                 }
266              };
267
268       aio_close $fh, $callback->($status)
269           Asynchronously close a file and call the callback with the result
270           code. WARNING: although accepted, you should not pass in a perl
271           filehandle here, as perl will likely close the file descriptor
272           another time when the filehandle is destroyed. Normally, you can
273           safely call perls "close" or just let filehandles go out of scope.
274
275           This is supposed to be a bug in the API, so that might change. It's
276           therefore best to avoid this function.
277
278       aio_read  $fh,$offset,$length, $data,$dataoffset, $callback->($retval)
279       aio_write $fh,$offset,$length, $data,$dataoffset, $callback->($retval)
280           Reads or writes "length" bytes from the specified "fh" and "offset"
281           into the scalar given by "data" and offset "dataoffset" and calls
282           the callback without the actual number of bytes read (or -1 on
283           error, just like the syscall).
284
285           The $data scalar MUST NOT be modified in any way while the request
286           is outstanding. Modifying it can result in segfaults or WW3 (if the
287           necessary/optional hardware is installed).
288
289           Example: Read 15 bytes at offset 7 into scalar $buffer, starting at
290           offset 0 within the scalar:
291
292              aio_read $fh, 7, 15, $buffer, 0, sub {
293                 $_[0] > 0 or die "read error: $!";
294                 print "read $_[0] bytes: <$buffer>\n";
295              };
296
297       aio_sendfile $out_fh, $in_fh, $in_offset, $length, $callback->($retval)
298           Tries to copy $length bytes from $in_fh to $out_fh. It starts read‐
299           ing at byte offset $in_offset, and starts writing at the current
300           file offset of $out_fh. Because of that, it is not safe to issue
301           more than one "aio_sendfile" per $out_fh, as they will interfere
302           with each other.
303
304           This call tries to make use of a native "sendfile" syscall to pro‐
305           vide zero-copy operation. For this to work, $out_fh should refer to
306           a socket, and $in_fh should refer to mmap'able file.
307
308           If the native sendfile call fails or is not implemented, it will be
309           emulated, so you can call "aio_sendfile" on any type of filehandle
310           regardless of the limitations of the operating system.
311
312           Please note, however, that "aio_sendfile" can read more bytes from
313           $in_fh than are written, and there is no way to find out how many
314           bytes have been read from "aio_sendfile" alone, as "aio_sendfile"
315           only provides the number of bytes written to $out_fh. Only if the
316           result value equals $length one can assume that $length bytes have
317           been read.
318
319       aio_readahead $fh,$offset,$length, $callback->($retval)
320           "aio_readahead" populates the page cache with data from a file so
321           that subsequent reads from that file will not block on disk I/O.
322           The $offset argument specifies the starting point from which data
323           is to be read and $length specifies the number of bytes to be read.
324           I/O is performed in whole pages, so that offset is effectively
325           rounded down to a page boundary and bytes are read up to the next
326           page boundary greater than or equal to (off-set+length).
327           "aio_readahead" does not read beyond the end of the file. The cur‐
328           rent file offset of the file is left unchanged.
329
330           If that syscall doesn't exist (likely if your OS isn't Linux) it
331           will be emulated by simply reading the data, which would have a
332           similar effect.
333
334       aio_stat  $fh_or_path, $callback->($status)
335       aio_lstat $fh, $callback->($status)
336           Works like perl's "stat" or "lstat" in void context. The callback
337           will be called after the stat and the results will be available
338           using "stat _" or "-s _" etc...
339
340           The pathname passed to "aio_stat" must be absolute. See API NOTES,
341           above, for an explanation.
342
343           Currently, the stats are always 64-bit-stats, i.e. instead of
344           returning an error when stat'ing a large file, the results will be
345           silently truncated unless perl itself is compiled with large file
346           support.
347
348           Example: Print the length of /etc/passwd:
349
350              aio_stat "/etc/passwd", sub {
351                 $_[0] and die "stat failed: $!";
352                 print "size is ", -s _, "\n";
353              };
354
355       aio_unlink $pathname, $callback->($status)
356           Asynchronously unlink (delete) a file and call the callback with
357           the result code.
358
359       aio_mknod $path, $mode, $dev, $callback->($status)
360           [EXPERIMENTAL]
361
362           Asynchronously create a device node (or fifo). See mknod(2).
363
364           The only (POSIX-) portable way of calling this function is:
365
366              aio_mknod $path, IO::AIO::S_IFIFO ⎪ $mode, 0, sub { ...
367
368       aio_link $srcpath, $dstpath, $callback->($status)
369           Asynchronously create a new link to the existing object at $srcpath
370           at the path $dstpath and call the callback with the result code.
371
372       aio_symlink $srcpath, $dstpath, $callback->($status)
373           Asynchronously create a new symbolic link to the existing object at
374           $srcpath at the path $dstpath and call the callback with the result
375           code.
376
377       aio_readlink $path, $callback->($link)
378           Asynchronously read the symlink specified by $path and pass it to
379           the callback. If an error occurs, nothing or undef gets passed to
380           the callback.
381
382       aio_rename $srcpath, $dstpath, $callback->($status)
383           Asynchronously rename the object at $srcpath to $dstpath, just as
384           rename(2) and call the callback with the result code.
385
386       aio_mkdir $pathname, $mode, $callback->($status)
387           Asynchronously mkdir (create) a directory and call the callback
388           with the result code. $mode will be modified by the umask at the
389           time the request is executed, so do not change your umask.
390
391       aio_rmdir $pathname, $callback->($status)
392           Asynchronously rmdir (delete) a directory and call the callback
393           with the result code.
394
395       aio_readdir $pathname, $callback->($entries)
396           Unlike the POSIX call of the same name, "aio_readdir" reads an
397           entire directory (i.e. opendir + readdir + closedir). The entries
398           will not be sorted, and will NOT include the "." and ".." entries.
399
400           The callback a single argument which is either "undef" or an array-
401           ref with the filenames.
402
403       aio_load $path, $data, $callback->($status)
404           This is a composite request that tries to fully load the given file
405           into memory. Status is the same as with aio_read.
406
407       aio_copy $srcpath, $dstpath, $callback->($status)
408           Try to copy the file (directories not supported as either source or
409           destination) from $srcpath to $dstpath and call the callback with
410           the 0 (error) or "-1" ok.
411
412           This is a composite request that it creates the destination file
413           with mode 0200 and copies the contents of the source file into it
414           using "aio_sendfile", followed by restoring atime, mtime, access
415           mode and uid/gid, in that order.
416
417           If an error occurs, the partial destination file will be unlinked,
418           if possible, except when setting atime, mtime, access mode and
419           uid/gid, where errors are being ignored.
420
421       aio_move $srcpath, $dstpath, $callback->($status)
422           Try to move the file (directories not supported as either source or
423           destination) from $srcpath to $dstpath and call the callback with
424           the 0 (error) or "-1" ok.
425
426           This is a composite request that tries to rename(2) the file first.
427           If rename files with "EXDEV", it copies the file with "aio_copy"
428           and, if that is successful, unlinking the $srcpath.
429
430       aio_scandir $path, $maxreq, $callback->($dirs, $nondirs)
431           Scans a directory (similar to "aio_readdir") but additionally tries
432           to efficiently separate the entries of directory $path into two
433           sets of names, directories you can recurse into (directories), and
434           ones you cannot recurse into (everything else, including symlinks
435           to directories).
436
437           "aio_scandir" is a composite request that creates of many sub
438           requests_ $maxreq specifies the maximum number of outstanding aio
439           requests that this function generates. If it is "<= 0", then a
440           suitable default will be chosen (currently 4).
441
442           On error, the callback is called without arguments, otherwise it
443           receives two array-refs with path-relative entry names.
444
445           Example:
446
447              aio_scandir $dir, 0, sub {
448                 my ($dirs, $nondirs) = @_;
449                 print "real directories: @$dirs\n";
450                 print "everything else: @$nondirs\n";
451              };
452
453           Implementation notes.
454
455           The "aio_readdir" cannot be avoided, but "stat()"'ing every entry
456           can.
457
458           After reading the directory, the modification time, size etc. of
459           the directory before and after the readdir is checked, and if they
460           match (and isn't the current time), the link count will be used to
461           decide how many entries are directories (if >= 2). Otherwise, no
462           knowledge of the number of subdirectories will be assumed.
463
464           Then entries will be sorted into likely directories (everything
465           without a non-initial dot currently) and likely non-directories
466           (everything else). Then every entry plus an appended "/." will be
467           "stat"'ed, likely directories first. If that succeeds, it assumes
468           that the entry is a directory or a symlink to directory (which will
469           be checked seperately). This is often faster than stat'ing the
470           entry itself because filesystems might detect the type of the entry
471           without reading the inode data (e.g. ext2fs filetype feature).
472
473           If the known number of directories (link count - 2) has been
474           reached, the rest of the entries is assumed to be non-directories.
475
476           This only works with certainty on POSIX (= UNIX) filesystems, which
477           fortunately are the vast majority of filesystems around.
478
479           It will also likely work on non-POSIX filesystems with reduced
480           efficiency as those tend to return 0 or 1 as link counts, which
481           disables the directory counting heuristic.
482
483       aio_rmtree $path, $callback->($status)
484           Delete a directory tree starting (and including) $path, return the
485           status of the final "rmdir" only.  This is a composite request that
486           uses "aio_scandir" to recurse into and rmdir directories, and
487           unlink everything else.
488
489       aio_fsync $fh, $callback->($status)
490           Asynchronously call fsync on the given filehandle and call the
491           callback with the fsync result code.
492
493       aio_fdatasync $fh, $callback->($status)
494           Asynchronously call fdatasync on the given filehandle and call the
495           callback with the fdatasync result code.
496
497           If this call isn't available because your OS lacks it or it
498           couldn't be detected, it will be emulated by calling "fsync"
499           instead.
500
501       aio_group $callback->(...)
502           This is a very special aio request: Instead of doing something, it
503           is a container for other aio requests, which is useful if you want
504           to bundle many requests into a single, composite, request with a
505           definite callback and the ability to cancel the whole request with
506           its subrequests.
507
508           Returns an object of class IO::AIO::GRP. See its documentation
509           below for more info.
510
511           Example:
512
513              my $grp = aio_group sub {
514                 print "all stats done\n";
515              };
516
517              add $grp
518                 (aio_stat ...),
519                 (aio_stat ...),
520                 ...;
521
522       aio_nop $callback->()
523           This is a special request - it does nothing in itself and is only
524           used for side effects, such as when you want to add a dummy request
525           to a group so that finishing the requests in the group depends on
526           executing the given code.
527
528           While this request does nothing, it still goes through the execu‐
529           tion phase and still requires a worker thread. Thus, the callback
530           will not be executed immediately but only after other requests in
531           the queue have entered their execution phase. This can be used to
532           measure request latency.
533
534       IO::AIO::aio_busy $fractional_seconds, $callback->()  *NOT EXPORTED*
535           Mainly used for debugging and benchmarking, this aio request puts
536           one of the request workers to sleep for the given time.
537
538           While it is theoretically handy to have simple I/O scheduling
539           requests like sleep and file handle readable/writable, the overhead
540           this creates is immense (it blocks a thread for a long time) so do
541           not use this function except to put your application under artifi‐
542           cial I/O pressure.
543
544       IO::AIO::REQ CLASS
545
546       All non-aggregate "aio_*" functions return an object of this class when
547       called in non-void context.
548
549       cancel $req
550           Cancels the request, if possible. Has the effect of skipping execu‐
551           tion when entering the execute state and skipping calling the call‐
552           back when entering the the result state, but will leave the request
553           otherwise untouched. That means that requests that currently exe‐
554           cute will not be stopped and resources held by the request will not
555           be freed prematurely.
556
557       cb $req $callback->(...)
558           Replace (or simply set) the callback registered to the request.
559
560       IO::AIO::GRP CLASS
561
562       This class is a subclass of IO::AIO::REQ, so all its methods apply to
563       objects of this class, too.
564
565       A IO::AIO::GRP object is a special request that can contain multiple
566       other aio requests.
567
568       You create one by calling the "aio_group" constructing function with a
569       callback that will be called when all contained requests have entered
570       the "done" state:
571
572          my $grp = aio_group sub {
573             print "all requests are done\n";
574          };
575
576       You add requests by calling the "add" method with one or more
577       "IO::AIO::REQ" objects:
578
579          $grp->add (aio_unlink "...");
580
581          add $grp aio_stat "...", sub {
582             $_[0] or return $grp->result ("error");
583
584             # add another request dynamically, if first succeeded
585             add $grp aio_open "...", sub {
586                $grp->result ("ok");
587             };
588          };
589
590       This makes it very easy to create composite requests (see the source of
591       "aio_move" for an application) that work and feel like simple requests.
592
593       * The IO::AIO::GRP objects will be cleaned up during calls to
594       "IO::AIO::poll_cb", just like any other request.
595       * They can be canceled like any other request. Canceling will cancel
596       not only the request itself, but also all requests it contains.
597       * They can also can also be added to other IO::AIO::GRP objects.
598       * You must not add requests to a group from within the group callback
599       (or any later time).
600
601       Their lifetime, simplified, looks like this: when they are empty, they
602       will finish very quickly. If they contain only requests that are in the
603       "done" state, they will also finish. Otherwise they will continue to
604       exist.
605
606       That means after creating a group you have some time to add requests.
607       And in the callbacks of those requests, you can add further requests to
608       the group. And only when all those requests have finished will the the
609       group itself finish.
610
611       add $grp ...
612       $grp->add (...)
613           Add one or more requests to the group. Any type of IO::AIO::REQ can
614           be added, including other groups, as long as you do not create cir‐
615           cular dependencies.
616
617           Returns all its arguments.
618
619       $grp->cancel_subs
620           Cancel all subrequests and clears any feeder, but not the group
621           request itself. Useful when you queued a lot of events but got a
622           result early.
623
624       $grp->result (...)
625           Set the result value(s) that will be passed to the group callback
626           when all subrequests have finished and set thre groups errno to the
627           current value of errno (just like calling "errno" without an error
628           number). By default, no argument will be passed and errno is zero.
629
630       $grp->errno ([$errno])
631           Sets the group errno value to $errno, or the current value of errno
632           when the argument is missing.
633
634           Every aio request has an associated errno value that is restored
635           when the callback is invoked. This method lets you change this
636           value from its default (0).
637
638           Calling "result" will also set errno, so make sure you either set
639           $!  before the call to "result", or call c<errno> after it.
640
641       feed $grp $callback->($grp)
642           Sets a feeder/generator on this group: every group can have an
643           attached generator that generates requests if idle. The idea behind
644           this is that, although you could just queue as many requests as you
645           want in a group, this might starve other requests for a potentially
646           long time.  For example, "aio_scandir" might generate hundreds of
647           thousands "aio_stat" requests, delaying any later requests for a
648           long time.
649
650           To avoid this, and allow incremental generation of requests, you
651           can instead a group and set a feeder on it that generates those
652           requests. The feed callback will be called whenever there are few
653           enough (see "limit", below) requests active in the group itself and
654           is expected to queue more requests.
655
656           The feed callback can queue as many requests as it likes (i.e.
657           "add" does not impose any limits).
658
659           If the feed does not queue more requests when called, it will be
660           automatically removed from the group.
661
662           If the feed limit is 0, it will be set to 2 automatically.
663
664           Example:
665
666              # stat all files in @files, but only ever use four aio requests concurrently:
667
668              my $grp = aio_group sub { print "finished\n" };
669              limit $grp 4;
670              feed $grp sub {
671                 my $file = pop @files
672                    or return;
673
674                 add $grp aio_stat $file, sub { ... };
675              };
676
677       limit $grp $num
678           Sets the feeder limit for the group: The feeder will be called
679           whenever the group contains less than this many requests.
680
681           Setting the limit to 0 will pause the feeding process.
682
683       SUPPORT FUNCTIONS
684
685       EVENT PROCESSING AND EVENT LOOP INTEGRATION
686
687       $fileno = IO::AIO::poll_fileno
688           Return the request result pipe file descriptor. This filehandle
689           must be polled for reading by some mechanism outside this module
690           (e.g. Event or select, see below or the SYNOPSIS). If the pipe
691           becomes readable you have to call "poll_cb" to check the results.
692
693           See "poll_cb" for an example.
694
695       IO::AIO::poll_cb
696           Process some outstanding events on the result pipe. You have to
697           call this regularly. Returns the number of events processed.
698           Returns immediately when no events are outstanding. The amount of
699           events processed depends on the settings of "IO::AIO::max_poll_req"
700           and "IO::AIO::max_poll_time".
701
702           If not all requests were processed for whatever reason, the file‐
703           handle will still be ready when "poll_cb" returns.
704
705           Example: Install an Event watcher that automatically calls
706           IO::AIO::poll_cb with high priority:
707
708              Event->io (fd => IO::AIO::poll_fileno,
709                         poll => 'r', async => 1,
710                         cb => \&IO::AIO::poll_cb);
711
712       IO::AIO::max_poll_reqs $nreqs
713       IO::AIO::max_poll_time $seconds
714           These set the maximum number of requests (default 0, meaning infin‐
715           ity) that are being processed by "IO::AIO::poll_cb" in one call,
716           respectively the maximum amount of time (default 0, meaning infin‐
717           ity) spent in "IO::AIO::poll_cb" to process requests (more cor‐
718           rectly the mininum amount of time "poll_cb" is allowed to use).
719
720           Setting "max_poll_time" to a non-zero value creates an overhead of
721           one syscall per request processed, which is not normally a problem
722           unless your callbacks are really really fast or your OS is really
723           really slow (I am not mentioning Solaris here). Using
724           "max_poll_reqs" incurs no overhead.
725
726           Setting these is useful if you want to ensure some level of inter‐
727           activeness when perl is not fast enough to process all requests in
728           time.
729
730           For interactive programs, values such as 0.01 to 0.1 should be
731           fine.
732
733           Example: Install an Event watcher that automatically calls
734           IO::AIO::poll_cb with low priority, to ensure that other parts of
735           the program get the CPU sometimes even under high AIO load.
736
737              # try not to spend much more than 0.1s in poll_cb
738              IO::AIO::max_poll_time 0.1;
739
740              # use a low priority so other tasks have priority
741              Event->io (fd => IO::AIO::poll_fileno,
742                         poll => 'r', nice => 1,
743                         cb => &IO::AIO::poll_cb);
744
745       IO::AIO::poll_wait
746           If there are any outstanding requests and none of them in the
747           result phase, wait till the result filehandle becomes ready for
748           reading (simply does a "select" on the filehandle. This is useful
749           if you want to synchronously wait for some requests to finish).
750
751           See "nreqs" for an example.
752
753       IO::AIO::poll
754           Waits until some requests have been handled.
755
756           Returns the number of requests processed, but is otherwise strictly
757           equivalent to:
758
759              IO::AIO::poll_wait, IO::AIO::poll_cb
760
761       IO::AIO::flush
762           Wait till all outstanding AIO requests have been handled.
763
764           Strictly equivalent to:
765
766              IO::AIO::poll_wait, IO::AIO::poll_cb
767                 while IO::AIO::nreqs;
768
769           CONTROLLING THE NUMBER OF THREADS
770
771       IO::AIO::min_parallel $nthreads
772           Set the minimum number of AIO threads to $nthreads. The current
773           default is 8, which means eight asynchronous operations can execute
774           concurrently at any one time (the number of outstanding requests,
775           however, is unlimited).
776
777           IO::AIO starts threads only on demand, when an AIO request is
778           queued and no free thread exists. Please note that queueing up a
779           hundred requests can create demand for a hundred threads, even if
780           it turns out that everything is in the cache and could have been
781           processed faster by a single thread.
782
783           It is recommended to keep the number of threads relatively low, as
784           some Linux kernel versions will scale negatively with the number of
785           threads (higher parallelity => MUCH higher latency). With current
786           Linux 2.6 versions, 4-32 threads should be fine.
787
788           Under most circumstances you don't need to call this function, as
789           the module selects a default that is suitable for low to moderate
790           load.
791
792       IO::AIO::max_parallel $nthreads
793           Sets the maximum number of AIO threads to $nthreads. If more than
794           the specified number of threads are currently running, this func‐
795           tion kills them. This function blocks until the limit is reached.
796
797           While $nthreads are zero, aio requests get queued but not executed
798           until the number of threads has been increased again.
799
800           This module automatically runs "max_parallel 0" at program end, to
801           ensure that all threads are killed and that there are no outstand‐
802           ing requests.
803
804           Under normal circumstances you don't need to call this function.
805
806       IO::AIO::max_idle $nthreads
807           Limit the number of threads (default: 4) that are allowed to idle
808           (i.e., threads that did not get a request to process within 10 sec‐
809           onds). That means if a thread becomes idle while $nthreads other
810           threads are also idle, it will free its resources and exit.
811
812           This is useful when you allow a large number of threads (e.g. 100
813           or 1000) to allow for extremely high load situations, but want to
814           free resources under normal circumstances (1000 threads can easily
815           consume 30MB of RAM).
816
817           The default is probably ok in most situations, especially if thread
818           creation is fast. If thread creation is very slow on your system
819           you might want to use larger values.
820
821       $oldmaxreqs = IO::AIO::max_outstanding $maxreqs
822           This is a very bad function to use in interactive programs because
823           it blocks, and a bad way to reduce concurrency because it is inex‐
824           act: Better use an "aio_group" together with a feed callback.
825
826           Sets the maximum number of outstanding requests to $nreqs. If you
827           to queue up more than this number of requests, the next call to the
828           "poll_cb" (and "poll_some" and other functions calling "poll_cb")
829           function will block until the limit is no longer exceeded.
830
831           The default value is very large, so there is no practical limit on
832           the number of outstanding requests.
833
834           You can still queue as many requests as you want. Therefore,
835           "max_oustsanding" is mainly useful in simple scripts (with low val‐
836           ues) or as a stop gap to shield against fatal memory overflow (with
837           large values).
838
839           STATISTICAL INFORMATION
840
841       IO::AIO::nreqs
842           Returns the number of requests currently in the ready, execute or
843           pending states (i.e. for which their callback has not been invoked
844           yet).
845
846           Example: wait till there are no outstanding requests anymore:
847
848              IO::AIO::poll_wait, IO::AIO::poll_cb
849                 while IO::AIO::nreqs;
850
851       IO::AIO::nready
852           Returns the number of requests currently in the ready state (not
853           yet executed).
854
855       IO::AIO::npending
856           Returns the number of requests currently in the pending state (exe‐
857           cuted, but not yet processed by poll_cb).
858
859       FORK BEHAVIOUR
860
861       This module should do "the right thing" when the process using it
862       forks:
863
864       Before the fork, IO::AIO enters a quiescent state where no requests can
865       be added in other threads and no results will be processed. After the
866       fork the parent simply leaves the quiescent state and continues
867       request/result processing, while the child frees the request/result
868       queue (so that the requests started before the fork will only be han‐
869       dled in the parent). Threads will be started on demand until the limit
870       set in the parent process has been reached again.
871
872       In short: the parent will, after a short pause, continue as if fork had
873       not been called, while the child will act as if IO::AIO has not been
874       used yet.
875
876       MEMORY USAGE
877
878       Per-request usage:
879
880       Each aio request uses - depending on your architecture - around 100-200
881       bytes of memory. In addition, stat requests need a stat buffer (possi‐
882       bly a few hundred bytes), readdir requires a result buffer and so on.
883       Perl scalars and other data passed into aio requests will also be
884       locked and will consume memory till the request has entered the done
885       state.
886
887       This is now awfully much, so queuing lots of requests is not usually a
888       problem.
889
890       Per-thread usage:
891
892       In the execution phase, some aio requests require more memory for tem‐
893       porary buffers, and each thread requires a stack and other data struc‐
894       tures (usually around 16k-128k, depending on the OS).
895

KNOWN BUGS

897       Known bugs will be fixed in the next release.
898

SEE ALSO

900       Coro::AIO.
901

AUTHOR

903        Marc Lehmann <schmorp@schmorp.de>
904        http://home.schmorp.de/
905
906
907
908perl v5.8.8                       2007-01-23                            AIO(3)
Impressum