I'm trying to synchronize reads and writes between processes(in the example I've used threads for convenience though) to a common file with c++ and I came up with this: the name of the file signals whose turn it is to write to the file. After one party is done writing, the file is renamed to signal that it's the other party's turn. This seems to work fine, however it seems that this is extremely slow(~0.5ms per write). Is there a better approach to this?
int main(int argc, char *argv[]) {
//create common file
std::ofstream file("buffTurnMain.txt");
file.close();
//thread writer
std::thread th([](){
for(int ii = 0; ii <10; ++ii) {
while(true) {//loop till threads turn
std::ifstream f("buffTurnThread.txt");
if (!f.fail()) { //break if successfully found
break;
}
}
std::ofstream fl;
fl.open("buffTurnThread.txt", std::ios_base::app);
fl << "hello from thread" << std::endl;
fl.close();
std::rename("buffTurnThread.txt", "buffTurnMain.txt");//after write rename to signal mains turn
}
});
//main writer
for(int ii = 0; ii < 10; ++ii) {
while(true) {//loop till mains turn
std::ifstream f("buffTurnMain.txt");
if (!f.fail()) { //break if successfully found
break;
}
}
std::ofstream fl;
fl.open("buffTurnMain.txt", std::ios_base::app);
fl << "hello from main" << std::endl;
fl.close();
std::rename("buffTurnMain.txt", "buffTurnThread.txt");//after write rename to signal threads turn
}
th.join();
}