-
Notifications
You must be signed in to change notification settings - Fork 0
/
ParallelSolver.cpp
73 lines (53 loc) · 1.54 KB
/
ParallelSolver.cpp
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
//
// Created by Armin on 13/04/2023.
//
#include <thread>
#include <iostream>
#include "ParallelSolver.h"
ParallelSolver::ParallelSolver(std::string const & input, int threads) : SudokuSolver(input), threads(threads) {
}
void ParallelSolver::addNextSteps(std::shared_ptr<SudokuMove> const & move, int x, int y) {
move->findNextAllowedMove(x, y);
for (int value = 1; value <= 9; ++value) {
if (move->isMoveAllowed(x, y, value)) {
computationQueue.push(Step(move, x, y, value));
}
}
}
void ParallelSolver::processNextStep() {
auto step = computationQueue.getAndPopBlocking();
if (step.end) {
return;
}
auto move = step.execute();
if (move->isSolved()) {
solutions.push_back(move);
return;
}
addNextSteps(move, step.x, step.y);
}
std::list<std::shared_ptr<SudokuMove>> ParallelSolver::solve() {
addNextSteps(baseMove, 0, 0);
bool running = true;
std::list<std::thread> workerThreads;
for (int i = 0; i < threads; ++i) {
std::thread workerThread([&] {
while (running) {
processNextStep();
}
});
workerThreads.push_back(std::move(workerThread));
}
std::thread mainThread([&] {
computationQueue.threadsWaiting(threads);
running = false;
for (int i = 0; i < threads; ++i) {
computationQueue.push(Step(true));
}
});
mainThread.join();
for (auto & thread : workerThreads) {
thread.join();
}
return solutions;
}