1
\$\begingroup\$

I would like to test reliability of system flock in a multi-threaded and concurrent environment as some suggest that they are not reliable (in comments).

Thus I wrote this code which requests non-blocking exclusive lock, with multiple threads at the same time (well, almost same time).

Is there better way to test flock mutex functionality, or how to be sure that it is always exclusive?

use strict;
use warnings;
use autodie;

use threads;
use Time::HiRes qw(time sleep);
use Fcntl qw(:flock);

sub fo{ my $fh; open($fh, ">", pop) && $fh }

my $t = time();
my $one = grep $_->join,
  map async {
    my $f = fo("/tmp/flock.test");
    sleep 2+$t-time();
    my $l = flock($f, LOCK_EX|LOCK_NB);
    sleep 1;
    return $l;
  }, 1..90;

# should always be 1
print "$one is 1\n";
\$\endgroup\$
  • 1
    \$\begingroup\$ Sorry, no. 1st: the comment you are referring to is simply wrong. File locks are mostly guaranteed to work, end of discussion. However, locks will generally be voluntary, and may not work on all filesystems. 2nd: locks are per-process, not per-thread. 3rd: I think you can write better code than that. Are you sure Code Review is the correct address? 4th: Your actual question is whether locks are reliable, and how to use them → ask on Stack Overflow. \$\endgroup\$ – amon Apr 4 '14 at 14:32
  • \$\begingroup\$ @amon tnx for comment; I was referring to OS&&FS on which they do work. Code above was my attempt to acquire more than one exclusive advisory lock (it did not happen). Do you have suggestion how to improve it? \$\endgroup\$ – mpapec Apr 4 '14 at 14:57

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.