同时读取两个不同的文件

Reading two different files simultaneously


我有 2 个文件,我希望每个核心读取自己的文件(每个文件有 5 行)并显示其内容
在此代码中,我有 2 个核心(core0、core1),输出核心 0 读取 core1 的内容(5 行)。 core1 从他的内容中读取了 4 行。

我试着让它像其他条件一样并且每个文件都有自己的 reader 但同样的问题仍然 exist.what 我应该怎么做?

    #include <vector>
#include <stdio.h>
#include <time.h>
#include <mpi.h>
#include <omp.h>
#include <fstream>
#include <iostream>
using namespace std;


void func2(int CoreID )
{

    int iFace;
    int iFaces=0;
    if (CoreID==0)
    {
        FILE* imgListFile = 0;
        char imgFilename[5012];
        char actualPath[90]="C:\DaliaDaliaSh\TrainingFiles\File10img_0_C";
        strcat(actualPath , "0.txt");
        imgListFile= freopen(actualPath , "r",stdin);
        while (fgets(imgFilename, 5012, imgListFile))
        {
            ++iFaces;
            printf( "** Core = %d , Path = %s\n" , CoreID , imgFilename );

        }
        rewind(imgListFile);
    }
    else if (CoreID==1)
    {
        FILE* imgListFile2 = 0;
        char imgFilename2[5012];
        char actualPath2[90]="C:\DaliaDaliaSh\TrainingFiles\File10img_0_C";
        strcat(actualPath2 , "1.txt");
        imgListFile2= freopen(actualPath2 , "r",stdin);
        while (fgets(imgFilename2, 5012, imgListFile2))
        {
            ++iFaces;
            printf( "** Core = %d , Path = %s\n" , CoreID , imgFilename2 );

        }
        rewind(imgListFile2);
    }


    //printf ("*ID = %d open actualPath= %s\n" , myId , actualPath);


    printf("core %d , iFaces= %d \n", CoreID , iFaces);
}
void main(int argc,char **argv)
{ 
    MPI::Init(argc,argv);
    int threadnum=2;
    omp_set_num_threads(threadnum);

#pragma omp parallel 
    {

        int CoreID = omp_get_thread_num();
        int x ; 

        func2(CoreID);

        cout <<"@@@@after call func inside pragma \n" ;

    }


    MPI ::Finalize();
}

您正在 stdin 进行 freopen。因此,两个核心将使用相同的流,并且文件读取将取决于哪个核心打开了流first/last [这是一个竞争条件]。

改为执行常规 fopen,它们不会发生冲突 [就像他们现在所做的那样]