This repository has been archived on 2024-12-15. You can view files and clone it, but cannot push or open issues or pull requests.
VectorSearch/parallel_finder.cpp

48 lines
1.5 KiB
C++
Raw Normal View History

#include "parallel_finder.h"
#include <mutex>
#include <thread>
using std::mutex, std::thread, std::lock_guard;
ParallelFinder::ParallelFinder(const vector<string> &word_list,
size_t thread_count)
: word_list_(word_list), thread_count_(thread_count) {}
vector<const string *>
ParallelFinder::find_prefix(string_view search_term) const {
vector<const string *> result;
mutex result_mutex;
vector<thread> threads;
for (size_t thread_index = 0; thread_index < thread_count_; ++thread_index) {
const size_t first_word_index =
thread_index * (word_list_.size() / thread_count_);
const size_t last_word_index =
(thread_index == thread_count_ - 1)
? word_list_.size()
: (thread_index + 1) * (word_list_.size() / thread_count_);
threads.emplace_back(
[](const vector<string> &word_list, const string_view &search_term,
vector<const string *> &result, size_t start_index, size_t end_index,
mutex &result_mutex) {
for (size_t index = start_index; index < end_index; ++index) {
const auto &current_word = word_list[index];
if (current_word.starts_with(search_term)) {
const lock_guard<mutex> lock(result_mutex);
result.push_back(&current_word);
}
}
},
cref(word_list_), cref(search_term), ref(result), first_word_index,
last_word_index, ref(result_mutex));
}
for (auto &thread : threads) {
thread.join();
}
return result;
}