c - 处理大文件时多线程程序崩溃
问题描述
我对 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);
我相信我没有为更大的文件分配足够的内存,或者我的指针使用不正确,任何帮助将不胜感激
解决方案
pthread_create(&thread[i], NULL, (void *) processFile, p);
这里i
假设正在计算线程,但是查看 for 循环......
for(int i = 0; i < fileSize; i = i + divide) {
i
实际上是输入文件内的位置,并且在第一次迭代之后远远超出了thread
数组的范围。
推荐阅读
- javascript - 具有基本 AuthType 的 CORS
- django - django:url路径问题
- python - 使用python通过outlook发送电子邮件时如何解决连接错误?
- java - 避免 MapStruct 中的重复映射
- regex - 在 rust 中连接两个正则表达式字符串
- javascript - handleSubmit 中的变量
- c# - (Unity)DirectoryNotFoundException - 如何将屏幕截图保存在外部文件夹中?
- python - Django 管理表单,设置 ArrayReference 字段时出现错误,Djongo
- linux - 如何验证 shell 脚本中文件的第一个字符?
- laravel - phpunit : 测试 api 并在同一个控制器中模拟一些方法,但模拟的方法不起作用