我正在嘗試在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