【问题标题】:C program not giving right outputC程序没有给出正确的输出
【发布时间】:2023-03-30 11:42:02
【问题描述】:
#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 个单词,这是不正确的,因为文本文件中有大约一百万个单词。谁能告诉我为什么它给我的字数不正确?谢谢!

【问题讨论】:

  • 您只查看缓冲区[0],它应该如何查看缓冲区的其余部分(因为 blockSize > 1)?

标签: c struct pthreads


【解决方案1】:

nthreads 的值在

中未定义
struct thread_data data[nthreads];

【讨论】:

  • 我以为我在上面声明它是一个 int。上面有 3 行。
  • 那么struct thread_data data[nthreads]; 中有多少元素?如果你没有声明它,你会得到一个编译器错误。您是否收到未初始化变量的编译器警告(@EOF 纠正了我)?
  • @WeatherVane 变量未初始化,值未指定。 使用该变量未定义。
  • 啊,我把它移到了线程数的扫描下方!现在当我运行它时,它在文件中显示 0 个单词,这是错误的,因为大约有 100 万个大声笑
  • @2501 如果你想挑剔,使用未初始化的变量是未定义的行为
猜你喜欢
  • 2012-09-07
  • 1970-01-01
  • 2017-10-24
  • 2022-06-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多