【发布时间】:2013-02-23 16:02:31
【问题描述】:
我有以下代码:
/*//not important
FILE * INFILE;
list_file = optarg;
if( ( INFILE = fopen( list_file, "a+" ) ) == NULL ) {
fprintf( stderr, "Can't open input file\n");
exit(0);
}
*/
pthread_mutex_t input_queue;
pthread_mutex_init(&input_queue, NULL);
for( i = 0 ; i < number_thread; i++)
{
if( pthread_create( &thread_id[i], NULL, &work, NULL) != 0 )
{
i--;
fprintf(stderr, RED "\nError in creating thread\n" NONE);
}
}
for( i = 0 ; i < number_thread; i++)
if( pthread_join( thread_id[i], NULL) != 0 )
{
fprintf(stderr, RED "\nError in joining thread\n" NONE);
}
void * work(void * data)
{
unsigned long line;
char buf[512];
while ( !feof(INFILE) )
{
pthread_mutex_lock(&input_queue);
fgets((char *)&buf, sizeof(buf), INFILE);
if (buf[strlen (buf) - 1] == '\n')
buf[strlen (buf) - 1] = '\0';
line = (unsigned long)buf;
pthread_mutex_unlock(&input_queue);
do_work( line );
}
fclose(INFILE);
return NULL;
}
它从文件中读取行,但一段时间后它意外退出,没有错误消息。 我想我搞砸了。
如何使用 pthreads 逐行读取文件,同时尽可能保持代码不变(我的意思是不要搞乱整个程序)?
【问题讨论】:
-
feof可能不像你想象的那样工作。 -
你为什么要这样做?这没有意义。
-
当然,这就是我在这里问这么多专家的原因。我是新手
-
fgets((char *)&buf, ...也有点奇怪 - 为什么不只是fgets(buf, ...? -
好吧,我在这里发布之前搜索了很多,我从其他相关问题中找到的片段中制作了代码:P
标签: c pthreads fopen fread pthread-join