###############################################################################
## ----------------------------------------------------------------------------
## Mutex - Various locking implementations supporting processes and threads.
##
###############################################################################

package Mutex;

use strict;
use warnings;

our $VERSION = '1.000';

## no critic (BuiltinFunctions::ProhibitStringyEval)
## no critic (TestingAndDebugging::ProhibitNoStrict)

use Carp ();

sub new {
    my $pkg; my ($class, %argv) = @_;

    if (defined $argv{'impl'}) {
        $pkg = $argv{'impl'};
    } else {
        $pkg = defined $argv{'path'} ? 'Flock' : 'Channel';
    }

    if (eval "require Mutex::$pkg; 1") {
        no strict 'refs';
        $pkg = 'Mutex::'.$pkg;

        return $pkg->new(%argv);
    }

    Carp::croak("Could not load implementation $pkg: $@\n");
}

sub impl {
    return $_[0]->{'impl'} || 'Not defined';
}

sub timedwait {
    my ($obj, $timeout) = @_;

    local $@; local $SIG{'ALRM'} = sub { alarm 0; die "timed out\n" };

    eval { alarm $timeout || 1; $obj->lock_exclusive };

    alarm 0;

    ( $@ && $@ eq "timed out\n" ) ? '' : 1;
}

1;

__END__

###############################################################################
## ----------------------------------------------------------------------------
## Module usage.
##
###############################################################################

=head1 NAME

Mutex - Various locking implementations supporting processes and threads

=head1 VERSION

This document describes Mutex version 1.000

=head1 SYNOPSIS

   {
       use Mutex;

       ( my $mutex = Mutex->new( path => $0 ) )->lock_exclusive;

       ...
   }

   {
       use threads;
       use Mutex;

       my $mutex = Mutex->new;

       threads->create('task', $_) for 1..4;
       $_->join for ( threads->list );
   }

   {
       use MCE::Hobo;
       use Mutex;

       my $mutex = Mutex->new;

       MCE::Hobo->create('task', $_) for 5..8;
       MCE::Hobo->waitall;
   }

   sub task {
       my ($id) = @_;
       $mutex->lock;

       # access shared resource
       print $id, "\n";
       sleep 1;

       $mutex->unlock;
   }

=head1 DESCRIPTION

This module implements locking methods that can be used to coordinate access
to shared data from multiple workers spawned as processes or threads.

The inspiration for this module came from reading Mutex for Ruby.

=head1 API DOCUMENTATION

=head2 Mutex->new ( )

=head2 Mutex->new ( impl => "Channel" )

=head2 Mutex->new ( impl => "Flock", [ path => "/tmp/file.lock" ] )

=head2 Mutex->new ( path => "/tmp/file.lock" )

Creates a new mutex.

Channel locking (the default), unless C<path> is given, is through a pipe
or socket depending on the platform. The advantage of channel locking is
not having to re-establish handles inside new processes and threads.

For Fcntl-based locking, it is the responsibility of the caller to remove
the C<tempfile>, associated with the mutex, when path is given. Otherwise,
it establishes a C<tempfile> internally including removal on scope exit.

=head2 $mutex->impl ( void )

Returns the implementation used for the mutex.

   my $m1 = Mutex->new( );
   my $m2 = Mutex->new( path => /tmp/my.lock );
   my $m3 = Mutex->new( impl => "Channel" );
   my $m4 = Mutex->new( impl => "Flock" );

   $m1->impl();  # Channel
   $m2->impl();  # Flock
   $m3->impl();  # Channel
   $m4->impl();  # Flock

=head2 $mutex->lock ( void )

=head2 $mutex->lock_exclusive ( void )

Attempts to grab an exclusive lock and waits if not available. Multiple calls
to mutex->lock by the same process or thread is safe. The mutex will remain
locked until mutex->unlock is called.

The method C<lock_exclusive> is an alias for C<lock>.

=head2 $mutex->lock_shared ( void )

Like C<lock_exclusive>, but attempts to grab a shared lock instead.
For non-Fcntl implementations, C<lock_shared> is an alias for C<lock>.

=head2 $mutex->unlock ( void )

Releases the lock. A held lock by an exiting process or thread is released
automatically.

=head2 $mutex->synchronize ( sub { ... }, @_ )

=head2 $mutex->enter ( sub { ... }, @_ )

Obtains a lock, runs the code block, and releases the lock after the block
completes. Optionally, the method is C<wantarray> aware.

   my $val = $mutex->synchronize( sub {
       # access shared resource
       return 'scalar';
   });

   my @ret = $mutex->enter( sub {
       # access shared resource
       return @list;
   });

The method C<enter> is an alias for C<synchronize>.

=head2 $mutex->timedwait ( timeout )

Blocks until obtaining an exclusive lock. A false value is returned
if the timeout is reached, and a true value otherwise. The default is
1 second when omitting timeout.

   my $mutex = MCE::Mutex::Flock->new( path => $0 );

   # terminate script if a previous instance is still running
   exit unless $mutex->timedwait( 2 );

   # script

   ...

=head1 REQUIREMENTS

The C<Mutex> module is supported from Perl 5.8.0 onwards.

=head1 AUTHOR

Mario E. Roy, S<E<lt>marioeroy AT gmail DOT comE<gt>>

=head1 COPYRIGHT AND LICENSE

Copyright (C) 2017 by Mario E. Roy

Mutex is released under the same license as Perl.

See L<http://dev.perl.org/licenses/> for more information.

=cut

