Visual C 多线程文件读取

Visual C Multithreaded file reading

我正在解析大约 8 GB,当然我想尽可能优化我的内存和处理器使用。我一次将一个文件读入缓冲区 1 页(4096 字节),它在大约 30 分钟内读取了整个文件(比 python 快了几个小时),但我想让它变得更好。我认为多线程是实现这一目标的方法,但我不知道如何在 C 中实现。我看到的示例令人印象深刻,但过于复杂。我希望有人可以归结为使用 C 的多线程功能的基本组件是什么,并提醒我将遇到的任何并发问题。感谢您提供的任何帮助。

澄清一下,我正在寻找的是非常基本的东西,例如创建 2 个线程,每个线程打印 4 次 hello world。

假设我有 4 个线程搜索 81920 字节(20 页)。

thread 1: searches page 1
thread 2: searches page 2
thread 3: searches page 3
thread 4: searches page 4
---assume they finish in order---
thread 1: searches page 5
thread 2: searches page 6
thread 3: searches page 7
thread 4: searches page 8
---assume they finish in order---
thread 1: searches page 9
thread 2: searches page 10
thread 3: searches page 11
thread 4: searches page 12
---assume they finish in order---
thread 1: searches page 13
thread 2: searches page 14
thread 3: searches page 15
thread 4: searches page 16
---assume they finish in order---
thread 1: searches page 17
thread 2: searches page 18
thread 3: searches page 19
thread 4: searches page 20

之所以如此重要,是因为对于 81920 字节中的每个字节(实际上我们想再添加大约 5 个 0,我调用 wcscpy 最多 5x

我想我找到了我正在寻找的东西:here 第二个例子是关于我正在寻找的复杂程度。我认为这样做谢谢。

将文件映射到内存中。有关如何执行此操作的详细信息,请参阅 MSDN 示例 "Creating a View Within a File"。你的用例有点不同,但原理是一样的,你最终会使用相同的 Windows 函数。 (如果您在 64 位进程中,您可能可以将整个文件映射到内存中;否则您需要将其映射到块中并处理匹配跨越多个块的情况。)

您可以使用CreateThread创建多个线程来分块处理数据。

I am reading an 8 GB binary file and searching for all occurrences of 5 specific wchar_t*

如果这就是您所做的全部,那么这个工作量几乎肯定会受到 I/O 限制,并且多线程可能会或可能不会帮助您。这种类型的子字符串搜索可以使用单次遍历所讨论的数据来完成,例如,使用 Knuth-Morris-Pratt for a single pattern or Aho-Corasick 用于多个模式。