开发者社区> 问答> 正文

C语言中的多线程字数统计

我知道我说过我会尝试自己解决这个问题,而我确实做到了,然后我先看了看别处,然后再次张贴在这里,但后来我却陷入了混乱:

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>

void partition_file(int n);
void *count_words(void *pos);

int total_count = 0;
int *seg_size = 0;

int main()
{
    int file=0;
    pthread_t tid;
    if((file=open("Device-Driver.txt",O_RDONLY)) < -1)
                return 1;
    partition_file(8);

    for (int i=0; i < 8; i++)
    {
        pthread_create(&tid, NULL, count_words, (void *) seg_size);
    }
    pthread_exit(NULL);
    return 0;

}

void partition_file(int n)
{
    int file=0;
    file=open("Device-Driver.txt",O_RDONLY);
    int size = lseek(file, 0, SEEK_END);
    seg_size = size / n);
    close(file);
}

void *count_words(void *pos)
{
    int file=0;
    int p = *((int *) pos);
    char buffer[seg_size];
    file=open("Device-Driver.txt",O_RDONLY);
    lseek(file,p,SEEK_SET); 
    read(file,buffer,seg_size);     
    for(int i = 0; i < size; i++)
    {
        if(buffer[i] == " ") total_count +=1;
    }
}

我应该如何最好地解决这个问题?特别是这些错误和警告:

展开
收起
祖安文状元 2020-01-07 14:22:21 437 0
1 条回答
写回答
取消 提交回答
  • seek仅移动读取指针。 将读取指针放在一个位置后,即可读取已读字符。

    我认为在您的练习中,每个线程都必须具有自己的读取指针。

    如果文件为800字节并分成8个字节: 线程1读取从0到99的字节, lseek(0,SEEK_SET),读取(文件,缓冲区,100),对缓冲区中的字计数...

    线程2:lseek(100,SEEK_SET),读取(文件,缓冲区, 100),计数缓冲区中的单词...

    线程3:lseek(200,SEEK_SET),读取(文件,缓冲区,100)计数缓冲区中的单词...

    等等...

    您不必创建临时文件

    分享改善这个答案

    2020-01-07 14:22:27
    赞同 展开评论 打赏
问答分类:
问答标签:
问答地址:
问答排行榜
最热
最新

相关电子书

更多
低代码开发师(初级)实战教程 立即下载
冬季实战营第三期:MySQL数据库进阶实战 立即下载
阿里巴巴DevOps 最佳实践手册 立即下载

相关实验场景

更多