ViewVC Help
View File | Revision Log | Show Annotations | Download File
/cvs/Coro/Event/Select.pm
Revision: 1.2
Committed: Sat Aug 20 01:09:19 2005 UTC (18 years, 9 months ago) by root
Branch: MAIN
CVS Tags: rel-1_2
Changes since 1.1: +1 -1 lines
Log Message:
*** empty log message ***

File Contents

# Content
1 =head1 NAME
2
3 Coro::Select - a (slow but event-aware) replacement for CORE::select
4
5 =head1 SYNOPSIS
6
7 use Coro::Select; # replace select globally
8 use Core::Select 'select'; # only in this module
9
10 =head1 DESCRIPTION
11
12 This module tries to create a fully working replacement for perl's
13 C<select> built-in, using C<Event> watchers to do the job, so other
14 coroutines can run in parallel.
15
16 To be effective globally, this module must be C<use>'d before any other
17 module that uses C<select>, so it should generally be the first module
18 C<use>'d in the main program.
19
20 You can also invoke it from the commandline as C<perl -MCoro::Select>.
21
22 =over 4
23
24 =cut
25
26 package Coro::Select;
27
28 use base Exporter;
29
30 use Coro;
31 use Event;
32
33 $VERSION = 1.3;
34
35 BEGIN {
36 @EXPORT_OK = qw(select);
37 }
38
39 sub import {
40 my $pkg = shift;
41 if (@_) {
42 $pkg->export(caller(0), @_);
43 } else {
44 $pkg->export("CORE::GLOBAL", "select");
45 }
46 }
47
48 sub select(;*$$$) { # not the correct prototype, but well... :()
49 if (@_ == 0) {
50 return CORE::select;
51 } elsif (@_ == 1) {
52 return CORE::select $_[0];
53 } elsif (defined $_[3] && !$_[3]) {
54 return CORE::select(@_);
55 } else {
56 my $current = $Coro::current;
57 my $nfound = 0;
58 my @w;
59 for ([0, 'r'], [1, 'w'], [2, 'e']) {
60 my ($i, $poll) = @$_;
61 if (defined (my $vec = $_[$i])) {
62 my $rvec = \$_[$i];
63 for my $b (0 .. (8 * length $vec)) {
64 if (vec $vec, $b, 1) {
65 (vec $$rvec, $b, 1) = 0;
66 push @w,
67 Event->io(fd => $b, poll => $poll, cb => sub {
68 (vec $$rvec, $b, 1) = 1;
69 $nfound++;
70 $current->ready;
71 });
72 }
73 }
74 }
75 }
76
77 push @w,
78 Event->timer(after => $_[3], cb => sub {
79 $current->ready;
80 });
81
82 Coro::schedule;
83 # wait here
84
85 $_->cancel for @w;
86 return $nfound;
87 }
88 }
89
90 1;
91
92 =back
93
94 =head1 AUTHOR
95
96 Marc Lehmann <schmorp@schmorp.de>
97 http://home.schmorp.de/
98
99 =cut
100
101