blob: 9c989927c4acdf4713d05d16388cd5b84e84b6dc (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
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])());
}
|