File Coverage

blib/lib/IO/Lambda/Flock.pm
Criterion Covered Total %
statement 29 29 100.0
branch 8 12 66.6
condition n/a
subroutine 8 8 100.0
pod 1 2 50.0
total 46 51 90.2


line stmt bran cond sub pod time code
1             # $Id: Flock.pm,v 1.8 2009/04/21 14:42:46 dk Exp $
2             package IO::Lambda::Flock;
3 1     1   963 use vars qw($DEBUG @ISA @EXPORT_OK);
  1         2  
  1         91  
4             @ISA = qw(Exporter);
5             @EXPORT_OK = qw(flock);
6             %EXPORT_TAGS = ( all => \@EXPORT_OK);
7             $DEBUG = $IO::Lambda::DEBUG{flock} || 0;
8              
9 1     1   4 use strict;
  1         2  
  1         21  
10 1     1   5 use warnings;
  1         1  
  1         25  
11 1     1   4 use Fcntl ':flock';
  1         22  
  1         108  
12 1     1   5 use IO::Lambda qw(:all :dev);
  1         2  
  1         268  
13 1     1   534 use IO::Lambda::Poll qw(poll_event);
  1         3  
  1         276  
14              
15             sub poll_flock
16             {
17 7     7 0 42 my ( $expired, $fh, $shared) = @_;
18 7 50       137 if ( CORE::flock( $fh, LOCK_NB | ($shared ? LOCK_SH : LOCK_EX) )) {
    100          
19 1 50       7 warn "flock $fh obtained\n" if $DEBUG;
20 1         7 return 1, 1;
21             }
22 6 100       25 return 1, 0 if $expired;
23 5         23 return 0;
24             }
25              
26             sub flock(&)
27             {
28             return this-> override_handler('flock', \&flock, shift)
29 2 50   2 1 20 if this-> {override}->{flock};
30              
31 2         8 my $cb = _subname flock => shift;
32 2         7 my ($fh, %opt) = context;
33 2 50       10 my $deadline = exists($opt{timeout}) ? $opt{timeout} : $opt{deadline};
34              
35             poll_event(
36             $cb, \&flock, \&poll_flock,
37             $deadline, $opt{frequency},
38             $fh, $opt{shared}
39 2         18 );
40             }
41              
42              
43             # The same code can be written way more elegant:
44             #
45             # sub flock(&)
46             # {
47             # poller {
48             # my %opt = @_;
49             # CORE::flock(
50             # $opt{fh},
51             # LOCK_NB | ($opt{shared} ? LOCK_SH : LOCK_EX
52             # );
53             # }
54             # -> call(context)
55             # -> condition(shift, \&flock, 'flock')
56             # }
57             #
58             # but will require another calling style:
59             #
60             # context fh => $fh, deadline => 5;
61             # flock { ok }
62              
63             1;
64              
65             __DATA__