Multithread ifstream/ofstream

Multithread ifstream/ofstream

本文关键字:ofstream ifstream Multithread      更新时间:2023-10-16

我有一个单独的"资源模块"类来管理我的应用程序的所有资源,它主要从一个文件"resources.DAT"中读取,其中所有内容都在。

所有从文件中请求新数据的对象都通过ResourceModule,这样我就可以管理内存并避免重复的资源。

void SomeFunction()
{
    Image* newImage = new Image();
    newImage->Load("imageName");
}
void Image::Load(string imageName)
{
    //Pointer to Image Data
    _myImage = ResourceModule::GetResource(imageName);
}

总是只有一个ResourceModule。我想让它成为多线程安全的,所以当调用GetResource(字符串资源名称)时,它不会出错。

如果我这样做:

Image* ResourceModule::GetResource(string imageName)
{
    ifstream fileReader;
    fileReader.open("RESOURCES.DAT", ios::binary);
    if(fileReader.is_open())
    {
        //Do the reading, return the pointer
    }
}

这个多线程安全吗?当我这样声明多个ifstream/ofstreams并从同一文件中读取时,它们是否相互冲突?

它将以只读方式工作,ifstream的每个实例都将读取。但这不会成为问题。每个ifstream在文件中都有自己的位置,并且并行进行。

你不需要做任何事情