C 访问多线程程序中的文件指针时出错

C 访问多线程程序中的文件指针时出错,c,file-io,parallel-processing,cilk,C,File Io,Parallel Processing,Cilk,我想问的是一些大代码的一部分,但我会尽量使它尽可能短。我将首先解释代码中的相关代码片段,然后解释我遇到的错误 从主功能内部的main.c: cilk_for ( line_count = 0; line_count != no_of_lines ; ++line_count ) { //some stuff here for ( j=line_count+1; j<no_of_lines; ++j ) { //some stuff here

我想问的是一些大代码的一部分,但我会尽量使它尽可能短。我将首先解释代码中的相关代码片段,然后解释我遇到的错误

从主功能内部的
main.c

cilk_for ( line_count = 0; line_count != no_of_lines ; ++line_count )
{
     //some stuff here
     for ( j=line_count+1; j<no_of_lines; ++j )
     {
         //some stuff here
         final_result[line_count][j] = bf_dup_eleminate ( table_bloom[line_count], file_names[j], j );
         //some stuff here
     }
     //some stuff here
}
bf_dup_eleminate_读取
bloom filter.c
文件:

int bf_dup_eleminate ( const bloom_filter *bf, const char *file_name, int j )
{
    int count=-1;
    FILE *fp = fopen (file_name, "rb" );
    if (fp)
    {
        count = bf_dup_eleminate_read ( bf, fp, j);
        fclose ( fp );
    }
    else
    {
        printf ( "Could not open file\n" );
    }
    return count;
}
int bf_dup_eleminate_read ( const bloom_filter *bf, FILE *fp, int j )
{
    //some stuff here
    printf ( "before while loop. j is %d ** workder id: **********%d***********\n", j, __cilkrts_get_worker_number());
    while (/*somecondition*/)
    {/*some stuff*/}
    //some stuff
}
这是一个多线程应用程序(我通过强制使用两个线程来运行它),我可以确保第一个线程到达
printf
语句(因为它是用线程信息输出的)。现在,
gdb
告诉我您有以下错误

bf_dup_eleminate_read(bf=)中的
0x0000000000406fc4,
fp=,
j=)在布卢姆过滤器处。c:536

第536行
int-bf\u-dup\u-eleminate\u-read(const-bloom\u-filter*bf,FILE*fp,int-j)

错误信息非常清楚,但我不明白为什么会发生这种情况。我想不出发生这种情况的原因。确保文件已打开(函数
bf_dup_eleminate
中的错误消息未打印)。我还相信,如果两个线程执行相同的代码行,那么它们将对所有局部变量进行单独的实例化。考虑到这一点,可能会有什么问题

感谢您的帮助

另外:
cilk\u for
关键字只是一个在运行时生成线程的构造


当要使用的线程数设为1时,程序运行。

就像通过引用传递变量一样,我的意思是table_bloom[line_count],它将指针传递给所有线程。因此,所有线程都试图同时访问指针值。您可以尝试复制每个参数,然后将其传递给bf_dup_eleminate_read。 未测试代码:

int bf_dup_eleminate ( const bloom_filter *bf, const char *file_name, int j )
{
    bloom_filter *t_bf = bf;

    int count=-1;
    FILE *fp = fopen (file_name, "rb" );
    if (fp)
    {
        count = bf_dup_eleminate_read (t_bf, fp, j);
        fclose ( fp );
    }
    else
    {
        printf ( "Could not open file\n" );
    }
    return count;
}
或者这不起作用,尝试制作每个参数的硬拷贝:

    bloom_filter t_bf = *bf; //forgot how struct copying is done
    char *t_filename = strdup(filename);
    int t_j = j; //not required

如果你不能复制,那么可以使用互斥锁。请参阅。

这是有道理的,但是您看到错误了吗
GDB
给出了它是关于
文件指针的
j
具体地说,它说bf=,fp=,j=没问题吗?我在这里对“没问题”有点困惑。还有一个疑问,你写了
bloom\u filter*t\u bf=bf
char*t_filename=filename但未使用它们我认为您的意思是将它们传递给函数
bf_dup_eleminate_read
,然后用
t_filename
打开文件。如果是,请编辑答案。GDB错误声明它无法访问所有传递参数的内存。bf、fp和j。这不仅仅是文件指针和j。