http://www.perlmonks.org?node_id=781689

willjones has asked for the wisdom of the Perl Monks concerning the following question:

Hello Monks, I have a situation where I believe I need some sort of atomic action protection for a section of code. I have a small file with a single value in it that is read by my CGI code and then checked for a specific value. If the value is not found then the file is updated to contain the value and a set of code is run and then execution ends. If the value is found then a different set of code is run (the file is not updated at all) and execution ends. My concern is what will happen if two CGI requests were to hit almost simultaneously so that the code that checks my file for the specific value occurs in the second thread before the first has a chance to update the file which would otherwise cause the second thread to be blocked from running that code. I came across flock here http://perldoc.perl.org/functions/flock.html and wondered if this would be the most appropriate solution for my situation or not. From what I read flock may or may not actually lock the file depending on the OS? Is this something I should be concerned with?

Does the following code make sense? Can I read and write after specifying LOCK_SH (or do I have to unlock and then re-lock with LOCK_EX?) Should this work if two processes were to hit my code at the same time?
#Lock my file... # Use LOCK_SH because I don't want the second thread to be able # to read until I'm done. flock( OUTFILE, LOCK_SH); seek( OUTFILE, 0, 2); # Why do I need this line? # Read from OUTFILE and if it has the right value then go ahead and # write the new value into it to indicate that the second process # should do something different, otherwise you are the second # process... unlock and do something different. # Now unlock... flock( OUTFILE, LOCK_UN);