gpt4 book ai didi

c - 为什么我的程序没有输出正确的字数?

转载 作者:太空宇宙 更新时间:2023-11-04 03:42:46 25 4
gpt4 key购买 nike

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

struct thread_data {
FILE *fp;
long int offset;
int start;
int blockSize;
//struct word maybe?
};

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') {
//newLine++;
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, x, id, blockSize, len;
//void *state;
FILE *fp;
pthread_t *threads;

fp = fopen("file1.txt", "r");

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;
//maybe data[id]. word struct
}
//LAST THREAD
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;
}

我在这个程序中修复了一个段错误,但现在当我运行它时,我得到 0 个单词,这是不正确的,因为文本文件中大约有一百万个单词。

谁能告诉我为什么它给我的字数统计不正确?

最佳答案

您遇到的一个问题是您在每个 countFrequency 线程中使用相同的文件描述符,每个线程执行一次 fseek,然后尝试循环读取。最后一个 fseek 获胜。

必须首先解决此设计缺陷。

关于c - 为什么我的程序没有输出正确的字数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27262924/

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