diff options
Diffstat (limited to 'oop2w5/Blackboard.cpp')
-rw-r--r-- | oop2w5/Blackboard.cpp | 48 |
1 files changed, 48 insertions, 0 deletions
diff --git a/oop2w5/Blackboard.cpp b/oop2w5/Blackboard.cpp new file mode 100644 index 0000000..9c98992 --- /dev/null +++ b/oop2w5/Blackboard.cpp @@ -0,0 +1,48 @@ +#include <algorithm> + +#include "Blackboard.h" + +using std::max; +using std::lock_guard; + +Blackboard::Blackboard() { + _bbs = new BlackboardStrategy(); +} + +Blackboard::~Blackboard() { + delete _bbs; +} + +void Blackboard::run() { + _subthreads[0] = new thread([this] { spawn_subthreads(0, 3); }); // 1, 2, 3 + _subthreads[1] = new thread([this] { spawn_subthreads(3, 3); }); // 4, 5, 6 + + _subthreads[0]->join(); + _subthreads[1]->join(); + + _bbs->setBestResult(max(_results[0], _results[1])); +} + +void Blackboard::spawn_subthreads(unsigned start_index, unsigned length) { + unsigned end_index = start_index + length; + // bereken geschiktheid strategie + for (unsigned i = start_index; i < end_index; i++) + _subsubthreads[i] = new thread([this, i] { _fitness[i] = (_bbs->*fitnessStrategies[i])(); }); + + // join alles + for (unsigned i = start_index; i < end_index; i++) + _subsubthreads[i]->join(); + + + // beslis beste strategie (lelijk linear zoeken want maar 3 elementen) + lock_guard<mutex>* bbs_lock = new lock_guard<mutex>(_bbs_lock); // lock guard + _bbs->setBestStrategy(_fitness[start_index]); // beste fitness altijd in _fitness + for (unsigned i = start_index; i < end_index; i++) + _bbs->setBestStrategy(max(_fitness[i], _bbs->getBestStrategy())); + unsigned best_index = start_index; + for (unsigned i = start_index; i < end_index; i++) + if (_fitness[i] == _bbs->getBestStrategy()) { best_index = i; break; } + delete bbs_lock; // handmatig mutex vrijgeven (want volgende regel code duurt lang) + + _results.push_back((_bbs->*resultStrategies[best_index])()); +} |