summaryrefslogtreecommitdiff
path: root/lib/MCE/Mutex.pm
blob: 9ab4fb464a0d1c749c96e4096c9fb0b8685ffea2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
###############################################################################
## ----------------------------------------------------------------------------
## Locking for Many-Core Engine.
##
###############################################################################

package MCE::Mutex;

use strict;
use warnings;

no warnings qw( threads recursion uninitialized );

our $VERSION = '1.888';

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

use Carp ();

## global Mutex used by MCE, MCE::Child, and MCE::Hobo inside threads
## on UNIX platforms

if ( $INC{'threads.pm'} && $^O !~ /mswin|mingw|msys|cygwin/i ) {
    $MCE::_GMUTEX = MCE::Mutex->new( impl => 'Channel' );
    MCE::Mutex::Channel::_save_for_global_cleanup($MCE::_GMUTEX);
}

sub new {
    my ($class, %argv) = @_;
    my $impl = defined($argv{impl})
        ? $argv{impl} : defined($argv{path}) ? 'Flock' : 'Channel';

    $impl = ucfirst( lc $impl );

    eval "require MCE::Mutex::$impl; 1;" ||
        Carp::croak("Could not load Mutex implementation '$impl': $@");

    my $pkg = 'MCE::Mutex::'.$impl;
    no strict 'refs';

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

## base class method

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

1;

__END__

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

=head1 NAME

MCE::Mutex - Locking for Many-Core Engine

=head1 VERSION

This document describes MCE::Mutex version 1.888

=head1 SYNOPSIS

 use MCE::Mutex;

 my $mutex = MCE::Mutex->new;

 {
     use MCE::Flow max_workers => 4;

     mce_flow sub {
         $mutex->lock;

         # access shared resource
         my $wid = MCE->wid; MCE->say($wid); sleep 1;

         $mutex->unlock;
     };
 }

 {
     use MCE::Hobo;

     MCE::Hobo->create('work', $_) for 1..4;
     MCE::Hobo->waitall;
 }

 {
     use threads;

     threads->create('work', $_)   for 5..8;
     $_->join for ( threads->list );
 }

 sub work {
     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 MCE::Mutex->new ( )

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

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

=head2 MCE::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.

 $m1 = MCE::Mutex->new( );
 $m1->impl();   # Channel

 $m2 = MCE::Mutex->new( path => /tmp/my.lock );
 $m2->impl();   # Flock

 $m3 = MCE::Mutex->new( impl => "Channel" );
 $m3->impl();   # Channel

 $m4 = MCE::Mutex->new( impl => "Flock" );
 $m4->impl();   # Flock

Current API available since 1.822.

=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>, available since 1.822.

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

=head2 $mutex->lock_shared ( void )

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

Current API available since 1.822.

=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>, available since 1.822.

=head2 $mutex->timedwait ( floating_seconds )

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.

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

 # terminate script if a previous instance is still running

 exit unless $mutex->timedwait( 2 );

 ...

Current API available since 1.822.

=head1 INDEX

L<MCE|MCE>, L<MCE::Core>

=head1 AUTHOR

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

=cut