多个线程使用ifstream读取同一文件(pthread)
Reading same file with ifstream by multiple threads (pthread)
我有一个函数,它由程序中创建的多个线程同时执行,并递归地创建更多线程来再次执行同一个函数。在这个函数中,我必须处理一个大文件。由于会有多个线程处理同一个文件,我想我必须为每个线程寻找文件的开头。这会将其他文件流也移动到文件的开头吗?会有什么问题吗?
void *myFunc(){
string lin;
ifstream ifs ("input.txt");
if(ifs){
ifs.seekg(0,ifs.beg);
while(getline(ifs,lin)){
...
do something
...
}
ifs.close();
}
pthread_t ptds[100];
int cc = 0;
if(some condition based on the above code){
for(int i=0;i<100;i++){
int rc = pthread_create(&ptds[cc++], NULL, myFunc, NULL);
if (rc){
cout << "Error:unable to create thread," << rc << endl;
exit(-1);
}
else{
cout << "Thread created" << endl;
}
}
void* status;
int rc;
for(int i=0; i < 100; i++ ){
rc = pthread_join(ptds[i], &status);
if (rc){
cout << "Error:unable to join," << rc << endl;
exit(-1);
}
}
}
}
我得到了一些模棱两可的结果。每次运行代码时,结果都会发生变化。我认为这与文件I/O同步有关。如何解决此问题?
如果您试图在多个线程中读取同一个文件对象,它们会破坏彼此的状态。我建议将文件读入内存一次(或内存映射),并让每个线程从内存中读取数据,这样他们就可以等待了。
相关文章:
- .cpp和.h文件中的模板专用化声明
- 为什么两个不同的未命名名称空间可以共存于一个cpp文件中
- 文本文件中的单词链表
- CMake-按正确顺序将项目与C运行时对象文件链接
- 使用新行和不使用新行读取文件
- 在C++程序中输入的文本文件将不起作用,除非文本被复制和粘贴
- 挂起和取消挂起一个文件DLL
- 如何确定我已使用非编码文件到达 EOF?
- 命名空间中具有.h和.cpp文件的类
- 如何使用ndk-build.cmd构建Android.so文件
- 从包含m行的文件中提取n行,必要时(惰性地)重复该文件
- 读取文件并输入到矢量中
- 在C++中查找文件
- c++库的公共头文件中应该包含什么
- 用c++从输入文件中读取另一行
- Cppcheck生成xml转储文件
- C++ 17:pthread的生成文件标志
- 多个线程使用ifstream读取同一文件(pthread)
- G++ 为什么你不必链接 iostream 二进制文件,但对于 pthread,你这样做了?
- 错误: C1083: 无法打开包含文件:"pthread.h": 没有此类文件或目录