我有以下代码:
/*//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 逐行读取文件但尽可能保持代码不变(我的意思是不要弄乱整个程序)?