我想问的是一些大代码的一部分,但我会尽量让它尽可能短。我将首先解释我的代码中的相关代码片段,然后再解释我遇到的错误。
来自 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_read
来自 bloom-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 536
是int bf_dup_eleminate_read ( const bloom_filter *bf, FILE *fp, int j )
错误信息很清楚,但我不明白为什么会这样。我想不出发生这种情况的原因。确定文件已打开(因为未打印函数 bf_dup_eleminate
中的错误消息)。我也相信,如果两个线程正在执行相同的代码行,那么它们将对所有局部变量进行单独的实例化。鉴于这可能是什么问题。
感谢任何帮助!!
附注:cilk_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
如果你不能复制,那么可以使用互斥锁。见link .
关于c - 在多线程程序中访问文件指针时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11266282/