Blocking Versus Nonblocking Behavior

In the file-locking examples we’ve seen previously, using Perl’s flock function and the Fcntl constants LOCK_SH and LOCK_EX, the default behavior has been to block on unsuccessful lock attempts. In other words, when a particular copy of our program fails to get a lock, it blocks, which means it sits there waiting for the lock to be granted. We can accomplish the same thing with a GDBM tie operation using an until loop, like so:

my %ANOTHER;

until (tie %ANOTHER, 'GDBM_File', $datafile, &GDBM_WRCREAT, 0644) {
    sleep 1;
}

This makes our script sleep for 1 second each time the tie fails, until it finally succeeds. (Notice how we had to take the my %ANOTHER declaration out of the tie statement, since we otherwise would be declaring %ANOTHER to be visible only inside the until block.)

We could omit the sleep 1 statement inside the until loop if we wanted to, in effect having an empty loop that just spins continuously until the tie succeeds. That seemed to me like a lot of work to put our computer through, however, since it might run that loop a million times or more each second while waiting for the tie to succeed. If we did want to write a “continuous” loop like that, though, a common Perl idiom would be to remove the block altogether, using the one-line form shown here:

1 until tie my %ANOTHER, 'GDBM_File', $datafile, &GDBM_WRCREAT, 0644;

In that statement, the initial numeral 1 is just a true value, evaluated and thrown away by Perl after each failure ...

Get Perl for Web Site Management now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.