From 56fd5eecbc7181c2cec6272211a06902edd4263f Mon Sep 17 00:00:00 2001 From: Henrik Hautakoski Date: Fri, 10 Jan 2020 07:31:45 +0100 Subject: [PATCH] src/main.cpp: in thread_search() handle edge case where number of search results is less than number of threads. --- src/main.cpp | 25 +++++++++++++++++++------ 1 file changed, 19 insertions(+), 6 deletions(-) diff --git a/src/main.cpp b/src/main.cpp index 8680fc6..f8ed9dd 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -43,12 +43,25 @@ static int n_threads = std::thread::hardware_concurrency(); #define search_func thread_search static void thread_search(const strlist_t& words, int n) { - // create n_threads - 1 as we use main process also. - std::vector t(n_threads - 1); - // divide the number of results for all threads. - int d = n / n_threads; - // Also calculate the reminder (will be assigned to the main thread) - int m = n % n_threads; + std::vector t; + int d, m; + + // We can use all threads + if (n >= n_threads) { + + // create n_threads - 1 as we use main process also. + t.resize(n_threads - 1); + // divide the number of results for all threads. + d = n / n_threads; + // Also calculate the reminder (will be assigned to the main thread) + m = n % n_threads; + } + // not enough results to use all threads. + else { + t.resize(n); + d = 1; + m = 0; + } // Launch threads. for(int i = 0; i < t.size(); i++) {