02/06/24 13:52
Perlメモのロック処理をクラスで包んでみた。
特徴
・むちゃくちゃ遅い
・アンロックし忘れがない
・処理全体をロックする場合に便利
・どの環境でも使用できる
#Lock.pm
package Lock;
use strict;
use File::Spec;
sub new{
my($class, %opt) = @_;
my %lfh = (
dir => ($opt{lockdir} || $opt{dir} || 'lock'),
file => ($opt{lockfile} || $opt{file} || 'lockfile'),
timeout => ($opt{timeout} || 60),
trytime => ($opt{trytime} || 10),
);
$lfh{path} = File::Spec->catfile($lfh{dir}, $lfh{file});
for(my $i = 0; $i < $lfh{trytime}; $i++, sleep(1))
{
return bless \%lfh => $class if(rename($lfh{path}, $lfh{current} = $lfh{path} . time));
}
local *LOCKDIR;
opendir(LOCKDIR, $lfh{dir}) or return undef;
while(my $file = readdir(LOCKDIR)){
if ($file =~ /^$lfh{file}(\d+)/){
return bless \%lfh => $class if (time - $1 > $lfh{timeout}
and rename(File::Spec->catfile($lfh{dir}, $file) => $lfh{current} = $lfh{path} . time));
last;
}
}
closedir LOCKDIR;
return undef;
}
sub DESTROY{ rename $_[0]->{current} => $_[0]->{path};}
1;
__END__