One might like to do flock manually or use a CPAN module. Meta::cpan is equipped with many flock modules. The Mutex module was made to work realiably with parallelization, supports threads and processes, including nested sessions.
The path option to Mutex constructs a Mutex::Flock object. One may specify the script path or a temporary path. Typically, the system flock requires read-write access to work. Thus, the Mutex module does a check and emits an error if the path isn't writeable by the calling process-userid.
use Mutex;
my $mutex = Mutex->new( path => $0 ); # choose $0 or tmp path
my $mutex = Mutex->new( path => "/tmp/db.lock" );
# The script terminates after some time if a previous
# instance is still running with a held lock.
exit unless $mutex->timedwait( 5 ); # seconds
# Has exclusive lock at this point. Due to using flock,
# the lock is released no matter how the process dies,
# even if omitting $mutex->unlock.
# Do DB insert here.
$mutex->unlock;
# Do other things, optionally.
...
The example lacks logic for storing the item to insert into a state file, in the event unable to obtain an exclusive lock. Running again with exclusive lock inserts pending items.
my $state_mutex = Mutex->new( path => "/tmp/state.lock" );
$state_mutex->enter( sub {
# Unable to obtain exclusive lock, then append pending inserts
# to a state file. Otherwise, read pending items, insert into DB,
# then unlink or empty the state file.
} );
Regards, Mario |