gpt4 book ai didi

C 多线程字数统计

转载 作者:行者123 更新时间:2023-11-30 19:40:00 24 4
gpt4 key购买 nike

所以我正在用 c 语言开发一个多线程字数统计程序,我的代码遇到了一些问题,在这里搜索时我发现了一个与我自己的项目类似的旧问题。我决定尝试让另一个代码正常工作,然后修改它以达到我想要的效果,而不是尝试重新编写充满问题的代码。该代码采用 txt 文件作为输入。问题是当您运行程序时出现段错误。代码如下:

#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>


struct thread_data{
FILE *fp;
long int offset;
int start;
int blockSize;
};

int words=0;

void *countFrequency(void* data){

struct thread_data* td=data;
char *buffer = malloc(td->blockSize);

int i,c;
i=0;c=0;
enum states { WHITESPACE, WORD };
int state = WHITESPACE;

fseek(td->fp, td->offset, td->start);

char last = ' ';
while ((fread(buffer, td->blockSize, 1, td->fp))==1){

if ( buffer[0]== ' ' || buffer[0] == '\t' ){
state = WHITESPACE;
}
else if (buffer[0]=='\n'){
state = WHITESPACE;
}
else {
if ( state == WHITESPACE ){
words++;
}
state = WORD;
}
last = buffer[0];
}
free(buffer);

pthread_exit(NULL);

return NULL;
}

int main(int argc, char **argv){

int nthreads, id, blockSize,len;
FILE *fp;
pthread_t *threads;


if (argc < 2){
fprintf(stderr, "Usage: ./a.out <file_path>");
exit(-1);
}

if((fp=fopen(argv[1],"r"))==NULL){
printf("Error opening file");
exit(-1);
}

printf("Enter the number of threads: ");
scanf("%d",&nthreads);
struct thread_data data[nthreads];
threads = malloc(nthreads*sizeof(pthread_t));

fseek(fp, 0, SEEK_END);
len = ftell(fp);
printf("len= %d\n",len);

blockSize=(len+nthreads-1)/nthreads;
printf("size= %d\n",blockSize);

for(id = 0; id < nthreads; id++){

data[id].fp=fp;
data[id].offset = blockSize;
data[id].start = id*blockSize+1;

}

data[nthreads-1].start=(nthreads-1)*blockSize+1;

for(id = 0; id < nthreads; id++)
pthread_create(&threads[id], NULL, &countFrequency,&data[id]);

for(id = 0; id < nthreads; id++)
pthread_join(threads[id],NULL);

fclose(fp);

printf("%d\n",words);
return 0;
}

这是原始帖子的链接:original

最佳答案

您通过在 struct thread_data data[nthreads]; 中使用具有自动存储持续时间 nthreads 的未初始化变量的不确定值来调用未定义的行为

尝试将行移到 scanf("%d",&nthreads); 之后。

关于C 多线程字数统计,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35930751/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com