Search code examples
c++countertransactional

c++ Permanent Offline Counter


I have an embedded server, which can be unplugged any time. Is there an elegant way to implement a transactional c++ counter? In the worst case it should return the previous ID.

I have an embedded server which periodically generates report files. The server does not have time or network connection, so I want to generate the report files incrementally. However, after the report files are downloaded I would like to delete the report files, while maintaining the counter:

report00001.txt
report00002.txt
report00003.txt
report00004.txt
// all the files have been deleted
report00005.txt
...

I would like to use a code like this:

 int last = read_current_id("counter.txt");
 last++;
 // transaction begin
 write_id("counter.txt", last);
 // transaction end

Solution

  • (assuming your server is running some sort of unixy operating system)

    You could try using the write-and-rename idiom for this.

    What you do is write your new counter value to a different file, say counter.txt~, then rename the temporary file onto the regular counter.txt. rename guarantees that either the new or old version of the file will exist at any time.

    You should also mount your filesystem with the sync option so that file contents are not buffered in RAM. Note however that this will reduce performance, and may shorten lifespan of flash memory.