I have a situation where two different processes (my C ++, the other made by other people in JAVA) are a writer and a reader from some common data file. So I tried to avoid the race state by writing a class like this (EDIT: this code is broken, it was just an example)
class ReadStatus { bool canRead; public: ReadStatus() { if (filesystem::exists(noReadFileName)) { canRead = false; return; } ofstream noWriteFile; noWriteFile.open (noWriteFileName.c_str()); if ( ! noWriteFile.is_open()) { canRead = false; return; } boost::this_thread::sleep(boost::posix_time::seconds(1)); if (filesystem::exists(noReadFileName)) { filesystem::remove(noWriteFileName); canRead= false; return; } canRead= true; } ~ReadStatus() { if (filesystem::exists(noWriteFileName)) filesystem::remove(noWriteFileName); } inline bool OKToRead() { return canRead; } };
using:
ReadStatus readStatus; //RAII FTW if ( ! readStatus.OKToRead()) return;
This is for one ofc program, the other will have a similar class. Idea: 1. check if another program created its file "I am the owner" if it has a breakthrough 2. 2. create a file "I am the owner", check again if another program created it if it deletes my file and breaks another 3. 3. do my reading, then delete my "I am the owner file."
Please note that the rare cases when they both do not read and do not write are okay, but the problem is that I still see a small chance of race conditions, because theoretically another program can check for the presence of my lock file, see that no one, then I create my own, another program creates my own, but before FS creates my file, I will check again, and this is not so, then a catastrophe occurs. That's why I added a 1 second delay, but as a CS nerd, I find that he is nervous so that the code works like this. Ofc. I do not expect anyone here to write me a solution, but I would be glad if someone knows a link to reliable code that I can use. PS It should be files, because I am not writing the whole project, and so it should be done.
PPS: access to the data file is not a reader, writer, reader, writer .... it can be a reader, reader, writer, writer, writer, reader, writer ....
PPS: another process is not written in C ++ :(, so boost is out of the question.