简体   繁体   中英

How should I implement an atomic sequence in Perl?

I have the following requirements:

  1. The sequence is unique to a host (no shared incrementing is necessary)
  2. The sequence must be monotonically increasing.
  3. The sequence must be persistent across processes.
  4. Incrementing the sequence must be atomic in the case of multiple processes working on it at the same time.
  5. Most of the time the file will be updated and the new value read after update. But, it should also be possible to read the current value without update.

I can hack together perl code that will do roughly this, but I'd like a more elegant solution.

Store the sequence number in a file and use flock to make sure only one process can access it:

sub set {     # seed the sequence number file
    my ($file, $number) = @_;
    open my $fh, '>', $file;
    print $fh $number;
}  # implicit close

sub get {
    my $file = shift;
    my $incr = @_ ? shift : 1;   # get($f) is like get($f,1)
    open my $lock, '>>', "$file.lock";
    flock $lock, 2;
    open my $fh, '<', $file;
    my $seq = <$fh>;
    close $fh;
    set($file, $seq+$incr) if $incr;   # update sequence number
    close $lock;
    return $seq;
}

You can call this as get($file,0) to retrieve the sequence number without changing it.

System time provides a monotonically increasing sequence, which addresses (2):

perl -MTime::HiRes=time -lwe "print time"

Until someone resets the clock...

Persistence (3) and atomicity of incrementations (4) seem to require a locking database. Berkeley DB comes to mind. But you might be looking for something simpler, unless you're already using it anyway. Read without update (5) would be no problem. A monotonically increasing sequence (2) wouldn't be either.

I'm not sure what you mean by "unique to a host" and "shared increment" (1). If it okay for sequence elements from different hosts to have the same value, then you can multiply the approach to all servers. Else you can have only one sequence that must be accessible to others via the network.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM