From 75553de490749a1d7fc858da4200331afa51044a Mon Sep 17 00:00:00 2001 From: Asriel Camora Date: Tue, 4 Jul 2023 09:25:32 +0200 Subject: [PATCH] Rudamentary locked multithreading 2x faster, but 8x threads.. not very good yet --- Benchmark/Program.cs | 4 ++-- Solver/Crafty/Solver.cs | 10 +++++++--- 2 files changed, 9 insertions(+), 5 deletions(-) diff --git a/Benchmark/Program.cs b/Benchmark/Program.cs index 6719530..bbe6cf3 100644 --- a/Benchmark/Program.cs +++ b/Benchmark/Program.cs @@ -47,8 +47,8 @@ internal static class Program var config = new SolverConfig() { - Iterations = 30_000,//1_000_000 - ThreadCount = 2, + Iterations = 30_000 / 8,//1_000_000 + ThreadCount = 8, }; var s = Stopwatch.StartNew(); diff --git a/Solver/Crafty/Solver.cs b/Solver/Crafty/Solver.cs index e10ac48..6ff0a70 100644 --- a/Solver/Crafty/Solver.cs +++ b/Solver/Crafty/Solver.cs @@ -129,6 +129,7 @@ public class Solver var s = new Vector(scoreSums); var m = new Vector(maxScores); var v = new Vector(visits); + v = Vector.Max(v, Vector.One); var exploitation = (W * (s / v)) + (w * m); var exploration = CVector * Intrinsics.ReciprocalSqrt(v); var evalScores = exploitation + exploration; @@ -151,13 +152,17 @@ public class Solver var node = RootNode; while (true) { + if (!Monitor.TryEnter(node, 5)) + return Select(); var expandable = node.State.AvailableActions.Count != 0; var likelyTerminal = node.Children.Count == 0; if (expandable || likelyTerminal) return node; // select the node with the highest score - node = EvalBestChild(node.State.Scores.Visits, CollectionsMarshal.AsSpan(node.Children)); + var n = EvalBestChild(node.State.Scores.Visits, CollectionsMarshal.AsSpan(node.Children)); + Monitor.Exit(node); + node = n; } } @@ -226,6 +231,7 @@ public class Solver var selectedNode = Select(); var (endNode, _, score) = ExpandAndRollout(simulator, selectedNode); + Monitor.Exit(selectedNode); Backpropagate(endNode, score); } @@ -235,9 +241,7 @@ public class Solver { var tasks = new Task[Config.ThreadCount]; for (var i = 0; i < Config.ThreadCount; ++i) - { tasks[i] = Task.Run(() => SearchThread(token), token); - } Task.WaitAll(tasks, token); }