首页 > 解决方案 > 处理大文件时多线程程序崩溃

问题描述

我对 C 语言非常陌生,我正在努力在我编写的程序中进行正确的内存管理和指针使用。

#include <time.h>
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include<string.h>
#include <pthread.h>
#include <assert.h>


struct argStruct {
    FILE *file;
    int start;
    int end;
};


void processFile(void *input)
{
    struct argStruct params = *(struct argStruct*) input;

//    FILE *textFile = params.file;
    int start = params.start;
    int end = params.end;


    printf("\nTHREAD - Start: %d | End: %d", start, end);

}



int main(int argc, char *argv[])
{
    FILE *pfile;
    int threadCount = 0, fileSize = 0, divide = 0;


    if (argc > 2)
    {
        pfile = fopen( argv[1], "r");
        threadCount = atoi(argv[2]);

        pthread_t * thread = malloc(sizeof(pthread_t)* threadCount);


        fseek(pfile, 0, SEEK_END);
        fileSize= ftell(pfile);
        fseek(pfile, 0, SEEK_SET);


        divide = (fileSize/threadCount);

        struct argStruct arguments;
        arguments.file = pfile;


        for(int i = 0; i < fileSize; i = i + divide) {

            arguments.start = i;
            arguments.end = i+divide;

            struct argStruct *p = malloc(sizeof *p);
            *p = arguments;

            pthread_create(&thread[i], NULL, (void *) processFile, p);

        }
        free(thread);
        pthread_exit(NULL);

        fclose(pfile);
        free(thread);

    } else {
        printf("Please enter text file name and number of threads");
    }


    return 0;
}

现在,我的程序的目标是获取一个文本文件,并根据文件大小和用户输入指定的线程数确定应该将文本文件分成多少。

然后它应该将文件和两个整数传递给 pthread_create,一个起点和终点。稍后我将添加更多功能,但现在我遇到了内存问题。

当我在中小型文本文件上运行我现在拥有的内容时,它可以正常工作。一个有 5 个线程的小文件有以下输出,这就是我想要的:

THREAD - Start: 0 | End: 1724
THREAD - Start: 1724 | End: 3448
THREAD - Start: 3448 | End: 5172
THREAD - Start: 5172 | End: 6896
THREAD - Start: 6896 | End: 8620
THREAD - Start: 8620 | End: 10344
Process finished with exit code 0

但是,当我使用大文本文件运行它时,我得到退出代码 11 和错误消息:分段错误:11

尝试使用调试器时,它会将我指向创建线程的行:

pthread_create(&thread[i], NULL, (void *) processFile, p);

我相信我没有为更大的文件分配足够的内存,或者我的指针使用不正确,任何帮助将不胜感激

标签: c

解决方案


pthread_create(&thread[i], NULL, (void *) processFile, p);

这里i假设正在计算线程,但是查看 for 循环......

for(int i = 0; i < fileSize; i = i + divide) {

i实际上是输入文件内的位置,并且在第一次迭代之后远远超出了thread数组的范围。


推荐阅读