简体   繁体   English

pthread_create启动例程未执行

[英]pthread_create start routine not executing

I'm trying to create a train station simulation for an assignment at school in C. This is an exercise in understanding threaded programming. 我正在尝试为C中的学校作业创建一个火车站模拟。这是理解线程编程的练习。 Here is my current code: 这是我当前的代码:

#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);
}

The code reads information about trains from a file trains.txt and creates a new thread for each line of the file(each train). 代码从文件trains.txt中读取有关火车的信息,并为文件的每一行(每个火车)创建一个新线程。

e:10,6
W:5,7
E:3,10

I would expect the output to be "Train Created!" 我希望输出为“ Train Created!”。 three times. 三次。 Compiling the code produces a Segmentation fault. 编译代码会产生分段错误。 What am I missing? 我想念什么?

 while (fgets(buff,10, ptr_file)!=NULL) {
        pthread_create(&trains[train_index], NULL, train_function, NULL);
        train_index++;
    }

Here, you are reading the file again but the file pointer was already at the end of the file since you have read the whole file before this while loop. 在这里,您正在重新读取文件但是文件指针已经在文件末尾,因为您已经在while循环之前读取了整个文件。 So you are not creating any threads at all but later trying to join (pthread_join calls) with non-existing threads. 因此,您根本不会创建任何线程,而是稍后尝试与不存在的线程连接 (pthread_join调用)。 This is undefined behaviour . 这是未定义的行为 You simply need to use train_count and create threads in a for loop: 您只需要使用train_count并在for循环中创建线程:

 for (int x = 0; x < train_count; x++) {
    pthread_create(&trains[x], NULL, train_function, NULL);
 }

Also, notice that the file reading part is flawed: 另外,请注意文件读取部分有缺陷:

while(!feof(ptr_file)) {...}

See Why is “while ( !feof (file) )” always wrong? 请参见为什么“ while(!feof(file))”总是错误的? for fixing it. 修复它。

there are several little problems with the code. 代码有几个小问题。

The following code eliminates statements that are not used in the posted code. 以下代码消除了发布代码中未使用的语句。

Do Not use feof() as a loop control. 不要将feof()用作循环控件。 For several reasons it fails as a loop control. 由于多种原因,它无法作为循环控制。

The necessary error checking is added to the code. 必要的错误检查已添加到代码中。

Notice the proper output of the correct error message to stderr via the use of the perror() function 注意通过使用perror()函数将正确的错误消息正确输出到stderr

Notice the proper error exiting via the use of the exit() function 注意通过使用exit()函数退出的正确错误

Notice the proper exit of main, at the end, via the use of the return() function 最后,通过使用return()函数注意main的正确退出

The following code is tested and works correctly. 以下代码已经过测试,可以正常工作。

#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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM