c++ - Verify a predicate in parallel, return as soon as a thread in a thread pool returns true -


i write function anyelementsatisfiespredicate takes in input predicate function p (that takes in input object of given type t , returns bool) , std::vector v of objects of type t, , returns true if , exists element in v s.t. p(v) == true.

this can accomplished means of loop:

bool anyelementsatisfiespredicate(std::function<bool(t&)> p, std::vector<t> v) {   (auto it=v.begin(); it!=v.end(); ++it)     if (p(*it))       return true;   return false; } 

this works fine (given defined type t) parallelize code testing predicate function p on different elements of vector v @ same time. idea split work among fixed (machine dependent) number of cores. each thread should evaluate predicate on different portion of original vector , return true finds predicate p holds on element in portion. given thread returns true, core function anyelementsatisfiespredicate should kill remaining threads , return true, if threads return false, should return false instead.

since code ran on different machines different number of cores prefer not introduce constant defining number of cores used, i'd rather have system choose best value me.

efficiency first concern. there easy way accomplish (maybe using boost threads library)?

not elegant solution in world, should work: (no boost, requires c++ 11)

#include <thread> #include <atomic>  template <typename t> struct pred_evaluator {     static void any_element_satisfies(const std::function<bool(const t&)> & pred, const typename std::vector<t>::iterator & begin, const typename std::vector<t>::iterator & end, std::atomic<bool> & result)      {         (const auto & it=begin; it!=end; ++it)         {             if (result || pred(*it))             {                 result= true;                 return;             }        }     }      static bool is_predicate_true_parallel(const std::function<bool(const t&)> & pred, const std::vector<t> & input, size_t num_threads)     {         size_t chunk_size = input.size() / 4;         std::atomic<bool> result(false);         std::vector<std::thread> threads;         (size_t = 0; < num_threads; ++i)         {             const auto & begin = input.begin() + *chunk_size;             const auto & end = input.begin() + std::min((i+1) * chunk_size, input.size());             threads.emplace_back(any_element_satisfies,pred,begin,end,result);         }          (auto & thread : threads)             thread.join();          return result;     } }; 

then, call pred_evaluator<t>::is_predicate_true_parallel predicate, vector, , number of threads input.


Comments