#include "parallel_finder.h" #include #include using std::mutex, std::thread, std::lock_guard; ParallelFinder::ParallelFinder(const vector &word_list, size_t thread_count) : word_list_(word_list), thread_count_(thread_count) {} vector ParallelFinder::find_prefix(string_view search_term) const { vector result; mutex result_mutex; vector 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 &word_list, const string_view &search_term, vector &result, size_t start_index, size_t end_index, mutex &result_mutex) { for (size_t index = start_index; index < end_index; ++index) { const auto ¤t_word = word_list[index]; if (current_word.starts_with(search_term)) { const lock_guard lock(result_mutex); result.push_back(¤t_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; }