【发布时间】:2013-09-04 05:38:19
【问题描述】:
我有一个“资源模块”类来管理我的应用程序的所有资源,它主要从一个文件“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(string resourceName) 被调用时,它不会出错。
如果我这样做:
Image* ResourceModule::GetResource(string imageName)
{
ifstream fileReader;
fileReader.open("RESOURCES.DAT", ios::binary);
if(fileReader.is_open())
{
//Do the reading, return the pointer
}
}
这种多线程安全吗?当我这样声明多个 ifstreams/ofstreams 并从 same 文件中读取它们时,它们是否会相互冲突?
【问题讨论】:
-
文件的读取可以同时进行;如果/当您决定要将读取的文件数据缓存在内存中(例如,以便第二次请求资源时,不必再次从磁盘读取),您需要序列化对数据的访问保存缓存数据的结构。
标签: c++ multithreading