How should I implement atomic sequence in Perl?

I have the following requirements:

  • The sequence is unique to the host (no additional increment required)
  • The sequence should be monotonically increasing.
  • The sequence must be constant between processes.
  • The sequence increment should be atomic in the case of several processes working on it at the same time.
  • In most cases, the file will be updated, and the new value will be read after the update. But it should also be possible to read the current value without updating.

I can crack a perl code that will do something like this, but I would like a more elegant solution.

+6
source share
2 answers

Save the sequence number in a file and use flock to make sure that only one process has access to 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 name it as get($file,0) to get the serial number without changing it.

+5
source

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

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

While someone is resetting the clock ...

Persistence (3) and atomicity of increments (4) seem to require a lock database. Berkeley comes to mind. But you can look for something simpler if you don't use it anyway. Reading without updating (5) would be a problem. A monotonically increasing sequence (2) would also not be.

I'm not sure what you mean by "unique to the host" and "general increment" (1). If for sequence elements from different hosts it is enough to have the same value, you can propagate the approach to all servers. In addition, you can have only one sequence, which should be available to other users through the network.

0
source

Source: https://habr.com/ru/post/890178/


All Articles