| 1 | ######################################################################## | ||
| 2 | # housekeeping | ||
| 3 | ######################################################################## | ||
| 4 | package LinkedList::Single::Example::Lock v2.0.0; | ||
| 5 | use v5.40; | ||
| 6 | |||
| 7 | use Carp qw( croak ); | ||
| 8 | use Time::HiRes qw( time ); | ||
| 9 | |||
| 10 | ######################################################################## | ||
| 11 | # methods | ||
| 12 | ######################################################################## | ||
| 13 | |||
| 14 | sub new( $class ) | ||
| 15 | { | ||
| 16 | bless | ||
| 17 | { | ||
| 18 | held => 0 | ||
| 19 | , acquired => 0 | ||
| 20 | , held_secs => 0 | ||
| 21 | } | ||
| 22 | => $class | ||
| 23 | } | ||
| 24 | |||
| 25 | ######################################################################## | ||
| 26 | # run $code with the lock held. | ||
| 27 | # | ||
| 28 | # there are no real threads here (perl ithreads clone their data and | ||
| 29 | # cannot share a linked list), so the lock is a stand-in that records | ||
| 30 | # what a real one would make other threads wait for: how many times it | ||
| 31 | # was taken, and for how long. | ||
| 32 | # | ||
| 33 | # the result is returned in scalar context. the lock is released | ||
| 34 | # whether or not $code dies. | ||
| 35 | ######################################################################## | ||
| 36 | |||
| 37 | sub hold( $self, $code, @arg ) | ||
| 38 | { | ||
| 39 | $self->{ held } | ||
| 40 | and croak 'Botched hold: the lock is not re-entrant'; | ||
| 41 | |||
| 42 | $self->{ held } = 1; | ||
| 43 | |||
| 44 | ++$self->{ acquired }; | ||
| 45 | |||
| 46 | my $start = time; | ||
| 47 | my $result; | ||
| 48 | |||
| 49 | my $ok | ||
| 50 | = eval | ||
| 51 | { | ||
| 52 | $result = $code->( @arg ); | ||
| 53 | |||
| 54 | 1 | ||
| 55 | }; | ||
| 56 | |||
| 57 | my $err = $@; | ||
| 58 | |||
| 59 | $self->{ held_secs } += time - $start; | ||
| 60 | $self->{ held } = 0; | ||
| 61 | |||
| 62 | $ok | ||
| 63 | or die $err; | ||
| 64 | |||
| 65 | $result | ||
| 66 | } | ||
| 67 | |||
| 68 | ######################################################################## | ||
| 69 | # introspection | ||
| 70 | ######################################################################## | ||
| 71 | |||
| 72 | sub acquired( $self ) | ||
| 73 | { | ||
| 74 | $self->{ acquired } | ||
| 75 | } | ||
| 76 | |||
| 77 | sub held_secs( $self ) | ||
| 78 | { | ||
| 79 | $self->{ held_secs } | ||
| 80 | } | ||
| 81 | |||
| 82 | sub reset( $self ) | ||
| 83 | { | ||
| 84 | $self->{ acquired } = 0; | ||
| 85 | $self->{ held_secs } = 0; | ||
| 86 | |||
| 87 | $self | ||
| 88 | } | ||
| 89 | |||
| 90 | 1 | ||
| 91 | __END__ |