并行同步使用文件名在UNIX上写入通用文件?
我正在尝试同步读取和写入过程之间的读写(虽然为了方便起见,但在我使用的示例中)与C ++的通用文件,我想到了:该文件信号的名称是将其轮到的文件信号写入文件。一方完成写作后,该文件被重命名,以表明轮到另一方了。这似乎很好,但是这似乎非常慢(每写约0.5ms)。有更好的方法吗?
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();
}
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();
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论