Minimizing chance of race conditions

Discussion in 'Perl Misc' started by Duke of Hazard, Nov 16, 2004.

  1. It is imperative that a section of my code is only executed by only
    one user at a time. So I have my program write a lock file when it
    reaches that section , then remove the lock file after it completes
    that section.

    This seemed to work ok, until I knew about race conditions. So I
    changed the code to write the lock file twice. First at the beginning
    of the script and second when it reaches the critical section of code
    that must be executed by only 1 user at a time.

    I figure this will significantly lower my probability of a race
    condition since two race conditions will need to occur simultaneously
    for it to break (which I am fine with, as long as it happens less than
    once per 1000 times).

    Is that right, or am I missing something?

    Thanks!
     
    Duke of Hazard, Nov 16, 2004
    #1
    1. Advertisements

  2. Duke of Hazard wrote:
    [...]
    Why don't you use code that does not have a race condition?
    "perldoc -q lock"

    jue
     
    Jürgen Exner, Nov 16, 2004
    #2
    1. Advertisements

  3. Also sprach Duke of Hazard:
    It's still wrong. Avoiding race conditions means that the chance of one
    occuring is zero. You merely lowered its probability. But if there is
    still a chance of a race condition, your code remains broken.

    You should only create one lockfile, but do it properly. It has to be an
    atomic operation:

    select undef, undef, undef, 0.5
    while ! sysopen LOCK, "file.lock", O_WRONLY|O_EXCL|O_CREAT;

    # once the program reaches this line, it succesfully acquired a
    # lock-file

    ...

    close LOCK;
    unlink "file.lock" or die "Something happened to the lock file: $!";

    The above, by the way, is reasonably portable.

    There's a number of FAQ entries dealing with locking. See

    perldoc -q lock

    Tassilo
     
    Tassilo v. Parseval, Nov 16, 2004
    #3
    1. Advertisements

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.