多个线程使用ifstream读取同一文件(pthread)

Reading same file with ifstream by multiple threads (pthread)

本文关键字:文件 pthread 读取 线程 ifstream      更新时间:2023-10-16

我有一个函数,它由程序中创建的多个线程同时执行,并递归地创建更多线程来再次执行同一个函数。在这个函数中,我必须处理一个大文件。由于会有多个线程处理同一个文件,我想我必须为每个线程寻找文件的开头。这会将其他文件流也移动到文件的开头吗?会有什么问题吗?

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同步有关。如何解决此问题?

如果您试图在多个线程中读取同一个文件对象,它们会破坏彼此的状态。我建议将文件读入内存一次(或内存映射),并让每个线程从内存中读取数据,这样他们就可以等待了。