http://qs321.pair.com?node_id=1148031


in reply to Atomic update counter in a file

You didn't say which operating system you're on, and the implementation details differ. But in general file systems just aren't atomic so these things are difficult, and they never work on network file systems.

However, you might find it easier to split this into 2 files, one just for the locking that you never need to remove so there's no race, and the other one for the data.

# pseudo code :) lock(.counter.lock); update(.counter); unlock(.counter.lock); # of course you need to read the counter under the lock too lock(.counter.lock); read(.counter); unlock(.counter.lock);

As long as everyone who accesses the counter uses the lock you should be ok