1#ifndef FSTCANDIDATEEVALUATORTHREADED_H
2#define FSTCANDIDATEEVALUATORTHREADED_H
51#include <condition_variable>
155template<
class RETURNTYPE,
typename DIMTYPE,
class SUBSET,
class CRITERION>
168 explicit Candidate_Evaluator_Threaded(
const unsigned int max_threads=2) :
_max_threads(max_threads),
initialized(false),
working(false),
tlocal(max_threads),
_processed_candidates(0),
_available_candidates(0),
_completed_candidates(0),
_pool_started(false),
_pshutdown(false),
_reading_result(0),
_callbacks_fired(false),
_batch_failed(false) {
169 assert(max_threads>0);
171 notify(
"Candidate_Evaluator_Threaded constructor.");
183 for(std::thread &w :
_pworkers)
if(w.joinable()) w.join();
185 notify(
"Candidate_Evaluator_Threaded destructor.");
199 virtual bool collect()
override;
210 virtual std::ostream&
print(std::ostream& os)
const override {os <<
"Candidate_Evaluator_Threaded(max_threads="<<
_max_threads<<
")";
return os;}
249 std::vector<CandidateResult>
cres;
268 enum StreamSlotState {SLOT_EMPTY=0, SLOT_PENDING, SLOT_RUNNING, SLOT_DONE, SLOT_FAILED};
280template<
class RETURNTYPE,
typename DIMTYPE,
class SUBSET,
class CRITERION>
286 assert(max_candidates>0);
317 if((DIMTYPE)(
cres.size())<max_candidates)
cres.resize(max_candidates);
329template<
class RETURNTYPE,
typename DIMTYPE,
class SUBSET,
class CRITERION>
346 assert(
tlocal[tidx].crit);
363template<
class RETURNTYPE,
typename DIMTYPE,
class SUBSET,
class CRITERION>
368 assert(sub->get_d()>0);
370 DIMTYPE local_available;
388 if(!
cres[local_available].sub ||
cres[local_available].sub->get_n()!=sub->get_n())
cres[local_available].sub.reset(
new SUBSET(sub->get_n()));
389 cres[local_available].sub->stateless_copy(*sub);
390 cres[local_available].feature=feature;
400template<
class RETURNTYPE,
typename DIMTYPE,
class SUBSET,
class CRITERION>
418 std::rethrow_exception(e);
426template<
class RETURNTYPE,
typename DIMTYPE,
class SUBSET,
class CRITERION>
433template<
class RETURNTYPE,
typename DIMTYPE,
class SUBSET,
class CRITERION>
441 sub=
cres[bestidx].sub;
442 result=
cres[bestidx].result;
443 feature=
cres[bestidx].feature;
447template<
class RETURNTYPE,
typename DIMTYPE,
class SUBSET,
class CRITERION>
462template<
class RETURNTYPE,
typename DIMTYPE,
class SUBSET,
class CRITERION>
475template<
class RETURNTYPE,
typename DIMTYPE,
class SUBSET,
class CRITERION>
485template<
class RETURNTYPE,
typename DIMTYPE,
class SUBSET,
class CRITERION>
489 assert(
tlocal[tidx].crit);
502 RETURNTYPE val=RETURNTYPE();
518template<
class RETURNTYPE,
typename DIMTYPE,
class SUBSET,
class CRITERION>
525 assert(bestsub->get_n()>0);
527 const DIMTYPE n=bestsub->get_n();
555 bool best_available=
false;
561 unsigned long long head=0, tail=0;
562 unsigned long long ordinal=0;
565 while(!gen_done && tail-head<W) {
566 const std::size_t t=(std::size_t)(tail%W);
568 if(!generator(*
_sslot_sub[t])) {gen_done=
true;
break;}
577 if(head==tail)
break;
579 const std::size_t h=(std::size_t)(head%W);
588 if(tracker) tracker->add(val,cand);
589 if(!best_available || better(val,cand,result,bestsub)) {
591 bestsub->stateless_copy(*cand);
593 if(on_best) on_best(-1,ordinal,val,cand);
615 std::rethrow_exception(e);
617 if(failed)
return false;
618 return best_available;
621template<
class RETURNTYPE,
typename DIMTYPE,
class SUBSET,
class CRITERION>
Abstract candidate-evaluation strategy: the seam through which one search algorithm body evaluates ca...
Implements concurrent evaluation of a criterion on a set of subset candidates.
Definition candidate_evaluator_threaded.hpp:156
std::condition_variable condition_available
wakes parked workers: new candidate available (or shutdown)
Definition candidate_evaluator_threaded.hpp:240
void finish_batch()
stops and joins workers, then fires pending per-result callbacks (once per batch)
Definition candidate_evaluator_threaded.hpp:401
std::list< std::size_t > _spending
pending slot indices in generation order
Definition candidate_evaluator_threaded.hpp:273
bool _pshutdown
destructor flag: workers drain pending work and exit
Definition candidate_evaluator_threaded.hpp:237
std::shared_ptr< SUBSET > PSubset
shared pointer to a candidate feature subset
Definition candidate_evaluator_threaded.hpp:160
parent::ResultCallback ResultCallback
see Candidate_Evaluator::ResultCallback
Definition candidate_evaluator_threaded.hpp:163
DIMTYPE _completed_candidates
candidates whose result is stored - batch done when it reaches _available_candidates
Definition candidate_evaluator_threaded.hpp:235
std::mutex mutex_candidate_getter
guards the candidate counters (workers claim/complete, master adds/waits)
Definition candidate_evaluator_threaded.hpp:239
PCriterion template_crit
to detect change of employed criterion inbetween search() calls
Definition candidate_evaluator_threaded.hpp:213
DIMTYPE _reading_result
iterating index for get*Result readers
Definition candidate_evaluator_threaded.hpp:251
void stream_worker(unsigned int tidx)
claims pending slots, evaluates with the worker's criterion clone
Definition candidate_evaluator_threaded.hpp:486
std::atomic< bool > _batch_failed
batch-mode twin of the sequential engine's _failed: a worker saw evaluate()==false
Definition candidate_evaluator_threaded.hpp:257
bool _sstop
shutdown flag for stream workers
Definition candidate_evaluator_threaded.hpp:277
virtual bool collect() override
completes the batch: waits for all evaluations and fires pending per-result callbacks in add-order
Definition candidate_evaluator_threaded.hpp:427
virtual std::ostream & print(std::ostream &os) const override
writes a human-readable identification of the engine; base default writes nothing
Definition candidate_evaluator_threaded.hpp:210
std::vector< ThreadLocal > tlocal
per-worker criterion clone + status, one entry per worker index; sized once in the constructor,...
Definition candidate_evaluator_threaded.hpp:222
std::condition_variable condition_batch_done
wakes the master: a candidate completed (finish_batch waits on the counter)
Definition candidate_evaluator_threaded.hpp:241
bool working
true while a batch is open (between initialize()/add_candidate() and finish_batch())
Definition candidate_evaluator_threaded.hpp:215
virtual bool is_threaded() const override
true for the threaded engine (any --threads value), false for the sequential one – distinguishes the ...
Definition candidate_evaluator_threaded.hpp:175
virtual bool add_candidate(const PSubset &sub, const DIMTYPE feature=0) override
adds candidate subset to the evaluation pool; returns false once the result storage reserved by initi...
Definition candidate_evaluator_threaded.hpp:364
std::mutex mutex_stream
guards the ring bookkeeping
Definition candidate_evaluator_threaded.hpp:274
bool initialized
true after the first initialize() call (guards clone (re)creation logic)
Definition candidate_evaluator_threaded.hpp:214
std::condition_variable _scv_work
wakes workers on new pending slots / shutdown
Definition candidate_evaluator_threaded.hpp:275
bool results_to_tracker(const PResultTracker tracker)
completes the batch and feeds every candidate's (value,subset) into tracker in add-order; false if th...
Definition candidate_evaluator_threaded.hpp:476
std::condition_variable _scv_done
wakes the master when a slot completes
Definition candidate_evaluator_threaded.hpp:276
parent::BestCallback BestCallback
see Candidate_Evaluator::BestCallback
Definition candidate_evaluator_threaded.hpp:164
std::exception_ptr _worker_exception
first exception a criterion threw on a worker; rethrown on the master after join
Definition candidate_evaluator_threaded.hpp:258
std::mutex mutex_worker_exception
guards _worker_exception (shared by batch and streaming workers; the modes never overlap)
Definition candidate_evaluator_threaded.hpp:259
Candidate_Evaluator< RETURNTYPE, DIMTYPE, SUBSET, CRITERION > parent
the abstract Candidate_Evaluator interface this class implements
Definition candidate_evaluator_threaded.hpp:158
ResultCallback _on_result
optional per-candidate callback, fired in add-order when the batch completes
Definition candidate_evaluator_threaded.hpp:253
Candidate_Evaluator_Threaded(const unsigned int max_threads=2)
Definition candidate_evaluator_threaded.hpp:168
parent::BetterPredicate BetterPredicate
see Candidate_Evaluator::BetterPredicate
Definition candidate_evaluator_threaded.hpp:165
virtual void initialize(const PCriterion &crit, const DIMTYPE max_candidates, ResultCallback on_result=ResultCallback()) override
Opens a new batch to be evaluated against crit, which must already be initialize()d....
Definition candidate_evaluator_threaded.hpp:281
const unsigned int _max_threads
size of the persistent worker pool, as given to the constructor
Definition candidate_evaluator_threaded.hpp:212
std::vector< CandidateResult > cres
one entry per batch candidate, indexed by add-order (the position add_candidate() assigned it)
Definition candidate_evaluator_threaded.hpp:249
virtual bool getBestResult(RETURNTYPE &result, PSubset &sub, DIMTYPE &feature) override
completes the batch, then returns (without copying sub contents) the candidate that yielded the highe...
Definition candidate_evaluator_threaded.hpp:434
std::vector< std::thread > _pworkers
Definition candidate_evaluator_threaded.hpp:231
parent::Generator Generator
see Candidate_Evaluator::Generator
Definition candidate_evaluator_threaded.hpp:162
DIMTYPE _available_candidates
to sychronize workers with adding new candidates to cres[]
Definition candidate_evaluator_threaded.hpp:234
void record_worker_exception()
captures the currently-handled exception (first one wins) for rethrow on the master by finish_batch()...
Definition candidate_evaluator_threaded.hpp:260
bool getNextResult(RETURNTYPE &result, PSubset &sub, DIMTYPE &feature)
advances the getFirstResult() iteration by one result; false once the batch is exhausted
Definition candidate_evaluator_threaded.hpp:463
std::shared_ptr< CRITERION > PCriterion
shared pointer to the criterion this engine evaluates candidates against
Definition candidate_evaluator_threaded.hpp:159
virtual void invalidate_clones() override
drops the cached per-worker criterion clones (see Candidate_Evaluator::invalidate_clones()); the next...
Definition candidate_evaluator_threaded.hpp:622
DIMTYPE _processed_candidates
candidates with finished processing, or being currently processed
Definition candidate_evaluator_threaded.hpp:233
StreamSlotState
Definition candidate_evaluator_threaded.hpp:268
void pooled_worker(unsigned int tidx)
the persistent worker loop: park, claim, evaluate, count, repeat
Definition candidate_evaluator_threaded.hpp:330
virtual unsigned int get_max_threads() const override
1 in the sequential implementation
Definition candidate_evaluator_threaded.hpp:174
bool _pool_started
the persistent pool exists (lazy spawn at first initialize())
Definition candidate_evaluator_threaded.hpp:236
std::shared_ptr< Result_Tracker< RETURNTYPE, SUBSET > > PResultTracker
shared pointer to the result tracker fed during evaluate_stream()
Definition candidate_evaluator_threaded.hpp:161
std::vector< PSubset > _sslot_sub
ring: master-generated candidates
Definition candidate_evaluator_threaded.hpp:270
std::vector< RETURNTYPE > _sslot_val
ring: evaluation results
Definition candidate_evaluator_threaded.hpp:271
std::vector< unsigned char > _sslot_state
ring: StreamSlotState per slot
Definition candidate_evaluator_threaded.hpp:272
bool _callbacks_fired
ensures _on_result fires exactly once per batch
Definition candidate_evaluator_threaded.hpp:254
virtual bool evaluate_stream(Generator generator, const PCriterion &crit, const PResultTracker tracker, BetterPredicate better, BestCallback on_best, RETURNTYPE &result, const PSubset bestsub) override
streaming mode: the master thread calls generator until exhaustion, workers evaluate concurrently,...
Definition candidate_evaluator_threaded.hpp:519
bool getFirstResult(RETURNTYPE &result, PSubset &sub, DIMTYPE &feature)
completes the batch and starts iteration over ALL of its results in ADD-ORDER (not by value); returns...
Definition candidate_evaluator_threaded.hpp:448
Abstract candidate-evaluation strategy (sequential-inline vs. thread-pooled).
Definition candidate_evaluator.hpp:86
std::function< void(const RETURNTYPE, const PSubset &, const DIMTYPE)> ResultCallback
fired once per evaluated batch candidate: (criterion value, candidate, feature tag as passed to add_c...
Definition candidate_evaluator.hpp:94
std::function< bool(SUBSET &)> Generator
fills sub with the next candidate, returns false when no candidate remains (in the threaded implement...
Definition candidate_evaluator.hpp:92
std::function< bool(const RETURNTYPE, const PSubset &, const RETURNTYPE, const PSubset &)> BetterPredicate
returns true if (value,subset) is better than (best value,best subset) - encodes per-search tie-break...
Definition candidate_evaluator.hpp:99
std::function< void(const int, const unsigned long long, const RETURNTYPE, const PSubset &)> BestCallback
Definition candidate_evaluator.hpp:97
Implements thread scheduler that assigns jobs up to maximum number of threads allowed.
Definition thread_pool.hpp:73
unsigned int go(const std::function< void()> &threadfunc)
Launches threadfunc in a free pool slot, blocking the caller until one becomes available if the pool ...
Definition thread_pool.hpp:94
void join_all()
Joins every currently running worker thread and resets the pool to empty (all slots free)....
Definition thread_pool.hpp:126
FST4 specific error passing class.
The Feature Selection Toolbox 4 library: every library component – data access, criteria and classifi...
Definition data_accessor.hpp:80
void notify(const std::string msg)
Prints msg followed by a newline via syncout::print(); a no-op unless the preprocessor macro DEBUG is...
Definition global.hpp:112
CriterionStatus
Lifecycle state of a worker's thread-local criterion clone (see Candidate_Evaluator_Threaded::ThreadL...
Definition candidate_evaluator_threaded.hpp:96
@ CRIT_READY
a clone exists and is not currently evaluating
Definition candidate_evaluator_threaded.hpp:98
@ CRIT_NONEXISTENT
no clone allocated yet for this worker slot
Definition candidate_evaluator_threaded.hpp:97
std::unique_ptr< T > clone_unique(const T &src)
Definition clonable.hpp:234
Defines interface for classes that enable collecting multiple results.
temporary storage of subset candidate evaluation results
Definition candidate_evaluator_threaded.hpp:244
DIMTYPE feature
the optional feature tag passed to add_candidate()
Definition candidate_evaluator_threaded.hpp:247
PSubset sub
the candidate subset (owned copy, not shared with the caller's subset)
Definition candidate_evaluator_threaded.hpp:246
RETURNTYPE result
the criterion value obtained for sub
Definition candidate_evaluator_threaded.hpp:245
thread-local storage of current subset candidate, criterion clone, and tracker clone
Definition candidate_evaluator_threaded.hpp:218
CriterionStatus status
CRIT_NONEXISTENT or CRIT_READY (see CriterionStatus).
Definition candidate_evaluator_threaded.hpp:220
PCriterion crit
this worker's private clone of the criterion (created lazily, reused across batches while the criteri...
Definition candidate_evaluator_threaded.hpp:219
Implements thread scheduler that assigns jobs up to maximum number of threads allowed.