1 |
=head1 NAME |
2 |
|
3 |
Coro::Signal - coroutine signals (binary semaphores) |
4 |
|
5 |
=head1 SYNOPSIS |
6 |
|
7 |
use Coro::Signal; |
8 |
|
9 |
$sig = new Coro::Signal; |
10 |
|
11 |
$sig->wait; # wait for signal |
12 |
|
13 |
# ... some other "thread" |
14 |
|
15 |
$sig->send; |
16 |
|
17 |
=head1 DESCRIPTION |
18 |
|
19 |
=over 4 |
20 |
|
21 |
=cut |
22 |
|
23 |
package Coro::Signal; |
24 |
|
25 |
use Coro (); |
26 |
|
27 |
$VERSION = 0.08; |
28 |
|
29 |
=item $s = new Coro::Signal; |
30 |
|
31 |
Create a new signal. |
32 |
|
33 |
=cut |
34 |
|
35 |
sub new { |
36 |
# [flag, [pid's]] |
37 |
bless [], $_[0]; |
38 |
} |
39 |
|
40 |
=item $s->wait |
41 |
|
42 |
Wait for the signal to occur. Returns immediately if the signal has been sent before. |
43 |
|
44 |
=cut |
45 |
|
46 |
sub wait { |
47 |
if ($_[0][0]) { |
48 |
$_[0][0] = 0; |
49 |
} else { |
50 |
push @{$_[0][1]}, $Coro::current; |
51 |
Coro::schedule; |
52 |
} |
53 |
} |
54 |
|
55 |
=item $s->send |
56 |
|
57 |
Send the signal, waking up a waiting process or remembering the signal. |
58 |
|
59 |
=cut |
60 |
|
61 |
sub send { |
62 |
if (@{$_[0][1]}) { |
63 |
(shift @{$_[0][1]})->ready; |
64 |
} else { |
65 |
$_[0][0] = 1; |
66 |
} |
67 |
} |
68 |
|
69 |
=item $s->broadcast |
70 |
|
71 |
Send the signal, waking up all waiting process. If no process is waiting the signal is lost. |
72 |
|
73 |
=cut |
74 |
|
75 |
sub broadcast { |
76 |
(shift @{$_[0][1]})->ready while @{$_[0][1]}; |
77 |
} |
78 |
|
79 |
=item $s->awaited |
80 |
|
81 |
Return true when the signal is beign awaited by some process. |
82 |
|
83 |
=cut |
84 |
|
85 |
sub awaited { |
86 |
!!@{$_[0][1]}; |
87 |
} |
88 |
|
89 |
1; |
90 |
|
91 |
=back |
92 |
|
93 |
=head1 AUTHOR |
94 |
|
95 |
Marc Lehmann <pcg@goof.com> |
96 |
http://www.goof.com/pcg/marc/ |
97 |
|
98 |
=cut |
99 |
|