【问题标题】:How to partition the contents in a buffer in C [closed]如何在C中对缓冲区中的内容进行分区[关闭]
【发布时间】:2014-10-03 02:09:05
【问题描述】:

我必须使用 Posix 在 C 中创建一个 wordcount 程序。我还必须使用 pthreads 使用多线程,方法是将输入文件读入缓冲区,然后根据要使用的线程数对该缓冲区进行分区。然后,每个线程应该计算其分区中的单词数。问题是我根本找不到任何来源来拆分或分区缓冲区中的内容。任何帮助都将不胜感激。

【问题讨论】:

  • 手动操作即可。一般来说,如果您的缓冲区有 80 个字符并且您有四个线程,则让线程 1 查看字符 0 - 19,线程 2 查看字符 20 - 39,依此类推。在您的情况下,由于您正在拆分单词,因此您必须查看这些边界以确保您不会在单词中间中断。
  • 如果你有 POSIX,你可以使用mmap() 将文件映射到内存,然后简单地给每个线程一个映射内存的一部分来处理。例如,四个线程,给每个 1/4 的内存来处理。您需要考虑起点和终点;如果一个词跨越两个线程之间的边界会发生什么?

标签: c multithreading pthreads posix partitioning


【解决方案1】:

假设您的程序将文件存储为指向字符数组的指针,您可以通过将缓冲区的“分区”表示为指向分区开头的指针和表示大小的整数来获得类似的结果分区。

下面的代码 sn-p 可以帮助您对缓冲区进行分区。

struct buffer_partition {
  char* start;
  int size;
}

void* word_count(void* arg) {
  struct buffer_partition* buffer=(struct buffer_partition*)arg;
  /* do word counting with buffer->start
     be careful to not access characters after buffer->size */    
}

int main() {
  /* read input */
  struct buffer_partition* partition = (struct buffer_partition*)malloc(sizeof(struct buffer_partition));
  partition->start=buffer+offset;
  partition->size=size_of_each_partition;
  pthread_create(thread_pointer, extra_attributes, word_count, partition);
  /* sum all results, print answer :) */
}

【讨论】:

  • 谢谢,这真的给了我一个很好的起点。
猜你喜欢
  • 1970-01-01
  • 2010-11-19
  • 2021-10-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-06-05
  • 1970-01-01
相关资源
最近更新 更多