[英]pthread_create start routine not executing
我正在尝试为C中的学校作业创建一个火车站模拟。这是理解线程编程的练习。 这是我当前的代码:
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <string.h>
#include <readline/readline.h>
void *train_function(void *args) {
printf("Train created!\n");
pthread_exit(0);
}
int main() {
FILE *ptr_file;
char buff[10];
int ch;
int train_count = 0;
ptr_file = fopen("./trains.txt", "r");
if (!ptr_file)
return 0;
/* Count number of trains */
while(!feof(ptr_file))
{
ch = fgetc(ptr_file);
if(ch == '\n')
{
train_count++;
}
}
pthread_t trains[train_count];
/* Create train for each line of file */
int train_index = 0;
while (fgets(buff,10, ptr_file)!=NULL) {
pthread_create(&trains[train_index], NULL, train_function, NULL);
train_index++;
}
fclose(ptr_file);
/* Wait for all trains to leave the station */
for (int x = 0; x < train_count; x++) {
pthread_join(trains[x], NULL);
}
exit(0);
}
代码从文件trains.txt中读取有关火车的信息,并为文件的每一行(每个火车)创建一个新线程。
e:10,6
W:5,7
E:3,10
我希望输出为“ Train Created!”。 三次。 编译代码会产生分段错误。 我想念什么?
while (fgets(buff,10, ptr_file)!=NULL) {
pthread_create(&trains[train_index], NULL, train_function, NULL);
train_index++;
}
在这里,您正在重新读取文件,但是文件指针已经在文件末尾,因为您已经在while循环之前读取了整个文件。 因此,您根本不会创建任何线程,而是稍后尝试与不存在的线程连接 (pthread_join调用)。 这是未定义的行为 。 您只需要使用train_count
并在for
循环中创建线程:
for (int x = 0; x < train_count; x++) {
pthread_create(&trains[x], NULL, train_function, NULL);
}
另外,请注意文件读取部分有缺陷:
while(!feof(ptr_file)) {...}
请参见为什么“ while(!feof(file))”总是错误的? 修复它。
代码有几个小问题。
以下代码消除了发布代码中未使用的语句。
不要将feof()用作循环控件。 由于多种原因,它无法作为循环控制。
必要的错误检查已添加到代码中。
注意通过使用perror()函数将正确的错误消息正确输出到stderr
注意通过使用exit()函数退出的正确错误
最后,通过使用return()函数注意main的正确退出
以下代码已经过测试,可以正常工作。
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <string.h>
//#include <readline/readline.h>
void *train_function(void *args __attribute__((unused)) )
{
printf("Train created!\n");
pthread_exit(0);
}
int main()
{
FILE *ptr_file;
int ch;
int train_count = 0;
ptr_file = fopen("trains.txt", "r");
if (!ptr_file)
{
perror( "fopen for trains.txt failed" );
exit( EXIT_FAILURE);
}
// implied else, fopen successful
/* Count number of trains */
while( (ch = fgetc(ptr_file) ) != EOF)
{
if(ch == '\n')
{
train_count++;
}
}
pthread_t trains[train_count];
/* Create train for each line of file */
int train_index = 0;
for ( train_index = 0; train_index < train_count; train_index++ )
{
if( pthread_create(&trains[train_index], NULL, train_function, NULL) )
{ // then pthread_create failed
perror( "pthread_create failed" );
exit( EXIT_FAILURE ); // this will cause all threads to also exit
}
// implied else, pthread_create successful
}
fclose(ptr_file);
/* Wait for all trains to leave the station */
for (int x = 0; x < train_count; x++)
{
pthread_join(trains[x], NULL);
}
return(0);
} // end function: main
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.