【发布时间】:2021-04-17 14:17:22
【问题描述】:
我想在一个非常大的文本文件(包含数十 GB 的文本)中查找一个字符串。我需要使用缓冲区和多线程,这就是我想做的:
- 在每次迭代时使用缓冲区创建一个循环读取文本块。
- 将块拆分为给定数量的线程。
- 每个线程都会在它收到的部分文本中搜索字符串。
- 如果找到字符串,则打印其位置,否则读取文本文件的另一块。
这是我尝试做的:
string[] lines = System.IO.File.ReadAllLines(@textfile);
int counter = lines.Length / nThreads;
int start = 0;
int end = counter;
(int,int)[] results = new (int, int)[nThreads];
results.ToList().ForEach(i => Console.WriteLine(i.ToString()));
for (int i = 0; i < nThreads; i++)
{
Thread thread1 = new Thread(() => { results[i] = ThreadSearch.SubarraySearch(StringToSearch, Delta, lines, start, end); });
// ThreadSearch - function that search the string in the array
thread1.Start();
thread1.Join();
}
// at the end i will go through the results array see if any of the threads found something
}
现在我在实现这个算法时有两个问题:
- 我现在不知道如何同时运行所有线程并在找到结果时停止。
- 我只知道如何使用缓冲区而不是文本中的块来逐行读取。
输入数据的约束和不变量:
- 我不知道文本文件的确切大小,只是它太大而无法一次读取,但我知道线程的最大缓冲区大小为 10k。
- 我正在搜索的字符串大小未知 - 可能是文本文件中的一个单词,它只包含字母和数字,没有空格或换行符。
我是 C# 的新手,所以任何帮助都会很棒。
【问题讨论】:
-
如果搜索到的文本恰好在两个连续缓冲区的边界处被分成两半怎么办?
-
指令是使用缓冲区读取文件(因为它太大而无法一次读取)并在 perellal 中使用多个线程来查找字符串
-
什么是“非常大” - 为可能的大小写一个示例。
-
线程最大缓冲区大小为10k
-
@Dana你想在帖子中添加新的细节,而不是在cmets中,新读者不一定会在cmets中搜索。
标签: c# multithreading search