0

I am programming a function quite like grep -r for a while now and need to return the local variables of my function. The thing is, I am supposed to invoke the function with thread pools using the CTPL library on ubuntu. Anyways, I am posting the function declaration with the given parameters.

std::vector<int>
grep_func(fs::path path_to_search, std::string search_str, std::string logfname, std::string txtfname)

Out of context, this function returns the information about where the searched word is found. The problem is that I am supposed to run this function with thread pools and get the thread IDs in a log file. But I also want to return the searched results to the main or another function to print the results.

I call this function from the main as below. (with the full awareness of it being wrong) Is there a way of achieving this?

ctpl::thread_pool p(num_of_threads); 
results = p.push(grep_func(cwd.string(), search, def_log_name, def_txt_name));
./grepx "word" -d [directory_name] -l [log_file] -r [result_file] [-t] [threads] 
```4
   I
---I this is how I execute the function. 

Victor Gubin
  • 2,782
  • 10
  • 24
persona
  • 70
  • 7
  • 1
    `std::async`. Example [here](https://stackoverflow.com/a/17973892/1563833) – Wyck Aug 24 '22 at 14:22
  • 1
    Use https://en.cppreference.com/w/cpp/thread/packaged_task, package your functions. Run the task on the threadpool and use the future object to get your results back. – Pepijn Kramer Aug 24 '22 at 14:23
  • 1
    @Wyck Yes but on Linux that will spool up a thread on each call (overhead), something the threadpool is trying to avoid. (On windows std::async does use a threadpool) – Pepijn Kramer Aug 24 '22 at 14:24
  • @PepijnKramer Just a quick follow-up question, this reference you are mentioning, in my case, void task_thread()'s return type will be std::vector task_thread() and inside the function, I will basically return, return result.get(), right ? – persona Aug 24 '22 at 15:30
  • 1
    The return value type will be the return type of grep_func. so `std::packaged_task>` and the future will be `std::future>` and yes you synchronize by calling `future.get()` which will be a blocking call so choose a good moment to call it (you might need to store it as member variable to use it later) – Pepijn Kramer Aug 24 '22 at 16:08
  • in each grep call, ./grepx "word" -d [directory_name] -l [log_file] -r [result_file] [-t] [threads] I send to this function different directories, and the name of the result files along with the number of threads, I am not sure how i can achieve this, I cannot simply call task_thread() without arguments right ? – persona Aug 24 '22 at 16:17

0 Answers0