C:将使用tmpfile()函数创建的临时文件与多线程合并

时间:2010-11-01 14:36:37

标签: c multithreading merge pthreads

我有n个文件,我的程序需要使用线程和临时文件将所有内容合并到一个文件中(必须使用tmpfile())。创建线程时,必须将2个文件合并到临时文件(temp1)中,然后另一个线程将下两个文件合并到另一个临时文件(temp2)中,依此类推,然后在下一级别另一个线程将temp1与temp2合并为另一个临时文件。

alt text

我正在考虑创建一个文件名数组,将其作为参数传递给pthread_create,该函数应该返回修改过的数组,但我无法弄清楚如何获取临时文件名。会是这样的:

int main(int argc, char *argv[]){

int n = argc -1;

char *files_arr[n];

pthread_t threads[n-1];

}

    for (int i=0; i < argc; i++)

    {
       pthread_create (&threads[i], NULL, temp_merge, (void *) &files_arr);
    }
}//end main

void *temp_merge (void *arg){

    char *myarray[];
    myarray = (char *) arg;
    FILE *f1, *f2, *tf;
    tf = tmpfile();

    //code to merge f1 and f2 into tf, f1 and f2 could be temp files created before

     pthread_exit((void*) myarray); //Do I lose the temp file using pthread_exit? 
}

问题是:如何在之前的线程中使用tmp()访问打开的临时文件以生成新的临时文件?

2 个答案:

答案 0 :(得分:1)

您可以使用tmpnam()代替tmpfile(),并根据需要手动打开/关闭/删除文件吗?

答案 1 :(得分:0)

您拥有要开始的文件列表(我假设),因此您将打开所有文件(返回FILE *)。

在mergesort函数(MSF)中,tmpfile()返回一个FILE *,这是你的MSF应该返回的。因此,MSF的返回值将成为您下一次调用MSF的两个输入之一。这种情况一直持续到你只有一个FILE *可以采取行动。