Skip to Main Content
Perl for Web Site Management
book

Perl for Web Site Management

by John Callender
October 2001
Beginner content levelBeginner
528 pages
15h 20m
English
O'Reilly Media, Inc.
Content preview from Perl for Web Site Management

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 ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Web Client Programming with Perl

Web Client Programming with Perl

Clinton Wong
Embedding Perl in HTML with Mason

Embedding Perl in HTML with Mason

Ken Williams, Dave Rolsky

Publisher Resources

ISBN: 1565926471Catalog PageErrata