我正在尝试在C语言中为学校的任务创建一个火车站模拟。这是一个了解线程编程的练习。这里是我当前的代码:pthread_create启动例程不执行
#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!”三次。编译代码会产生分段错误。我错过了什么?
尝试void train_function(void * args)而不是 – Thomas
使用调试器来找出seg故障发生的位置。至少应该防止“列车”阵列溢出。你认为你的逻辑是正确的,并且'train_count'被正确设置。这是一个危险的假设,并且健壮的代码至少可以抵御'fgets'循环。 – kaylum