2012-06-29 46 views
1

我想问的是一些大代码的一部分,但我会尽量缩短它的大小。我将首先从我的代码中解释相关的代码片段,然后解释我遇到的错误。错误访问多线程程序中的文件指针

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; 
} 

bf_dup_eleminate_readbloom-filter.c文件:

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告诉我,你有以下错误

0x0000000000406fc4 in bf_dup_eleminate_read (bf=<error reading variable: Cannot access memory at address 0x7ffff7edba58>, fp=<error reading variable: Cannot access memory at address 0x7ffff7edba50>, j=<error reading variable: Cannot access memory at address 0x7ffff7edba4c>) at bloom-filter.c:536

Line 536int bf_dup_eleminate_read (const bloom_filter *bf, FILE *fp, int j)

的错误信息是很清楚,但我没有得到这为什么会发生。我想不出为什么会发生这种情况。确定文件已打开(因为功能bf_dup_eleminate中的错误消息未打印)。另外我相信,如果两个线程正在执行相同的代码行,那么它们将为所有局部变量分别实例化。鉴于可能是什么问题。

任何帮助表示赞赏!

P.S .: cilk_for关键字只是一个构造,用于在运行时产生线程。

程序时由要使用的线程数1

回答

0

好像当你通过引用传递变量,我的意思是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 

如果不能进行复制,那么也许使用互斥。见link

+0

这可能是有道理的,但你看到错误'GDB'给它说的是'文件指针'和'j'具体是 –

+0

它说bf = <读取变量的错误:无法访问地址0x7ffff7edba58>处的内存,fp = <错误读取变量:无法访问地址0x7ffff7edba50>处的内存,j = <读取错误变量:无法访问地址0x7ffff7edba4c处的内存>那好吗? – ArmenB

+0

我在这里有点困惑,“那好吧?”。你能否详细说明 –