in reply to Re: Faster locking
in thread Faster locking

Thank you! I dropped the .lock file and am now locking the script itself. It appears I can lock it again, with no apparent side effect, if it was locked earlier. Found a neat way of referencing the running script without using DATA but now can't find the site to reference it.

The lock_retrieve and lock_nstore were intended to keep other processes waiting, whilst the updated data is being flushed to the cache file.

Herewith the resulting script snippet:

my $cache_ttl = 60; my $cachefile = '/tmp/mtapi.'.$router.'.cache'; my %bgp_peer; my $cached = 0; my $modified = (stat($cachefile))[9]; open our $lockfile, '<', $0 || die $!; if (defined $modified) { if (($modified >= (time-$cache_ttl)) || (!flock $lockfile, LOCK_EX | + LOCK_NB)) { if (%bgp_peer = %{lock_retrieve($cachefile)}) { $cached = 1 }; } } if ($cached == 0) { if (!flock $lockfile, LOCK_EX | LOCK_NB) { print STDERR "Another pro +cess is already using MikroTik API.\n"; exit 6 }; $api->connect(); $api->login(); %bgp_peer = $api->get_by_key('/routing/bgp/peer/print', 'name'); $api->logout(); lock_nstore \%bgp_peer, $cachefile; chmod 0660, $cachefile; flock $lockfile, LOCK_UN; }

Replies are listed 'Best First'.
Re^3: Faster locking
by bbs2web (Acolyte) on Apr 04, 2017 at 08:16 UTC

    Could someone please confirm that Perl would skip trying to acquire a lock when the first 'if' condition is true?

    Should I rather place the test in to a nested condition, completely outside of the first?

    if ( (1 == 1) || (!flock $lockfile, LOCK_EX | LOCK_NB) )

    PS: Things appear to be working as expected, but I would still like to know, for my own peace of mind.

      Okay, so it works as expected:

      Test code:

      #!/usr/bin/perl use strict; use warnings; use Fcntl qw(:flock); open our $lockfile, '<', $0 || die $!; if ( (1 == 1) || (!flock $lockfile, LOCK_EX | LOCK_NB) ) { print "in loop\n"; sleep 30; if (flock $lockfile, LOCK_EX | LOCK_NB) { print "locked\n"; } else { print "not locked\n"; } sleep 30; }

      First instance:

      in loop locked

      Second instance:

      in loop not locked