From 72bd9ee812494b579a5084614b4be869f6de0851 Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Sun, 19 Feb 2023 07:16:52 +0100 Subject: [PATCH] Finished multithreading --- Cargo.lock | 31 ++++++++++++++- Cargo.toml | 1 + src/craft.rs | 8 ++-- src/main.rs | 103 ++++++++++++++++++++++++++++---------------------- src/solver.rs | 4 +- 5 files changed, 94 insertions(+), 53 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 639bab1..10defab 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -78,6 +78,15 @@ version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2540771e65fc8cb83cd6e8a237f70c319bd5c29f78ed1084ba5d50eeac86f7f9" +[[package]] +name = "hermit-abi" +version = "0.2.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ee512640fe35acbfb4bb779db6f0d80704c2cacfa2e39b601ef3e3f47d1ae4c7" +dependencies = [ + "libc", +] + [[package]] name = "hermit-abi" version = "0.3.1" @@ -100,7 +109,7 @@ version = "0.4.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "22e18b0a45d56fe973d6db23972bf5bc46f988a4a2385deac9cc29572f09daef" dependencies = [ - "hermit-abi", + "hermit-abi 0.3.1", "io-lifetimes", "rustix", "windows-sys", @@ -124,6 +133,16 @@ version = "0.1.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f051f77a7c8e6957c0696eac88f26b0117e54f52d3fc682ab19397a8812846a4" +[[package]] +name = "num_cpus" +version = "1.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0fac9e2da13b5eb447a6ce3d392f23a29d8694bff781bf03a16cd9ac8697593b" +dependencies = [ + "hermit-abi 0.2.6", + "libc", +] + [[package]] name = "once_cell" version = "1.17.1" @@ -252,6 +271,15 @@ dependencies = [ "winapi-util", ] +[[package]] +name = "threadpool" +version = "1.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d050e60b33d41c19108b32cea32164033a9013fe3b46cbd4457559bfbf77afaa" +dependencies = [ + "num_cpus", +] + [[package]] name = "toml" version = "0.5.9" @@ -378,5 +406,6 @@ dependencies = [ "lazy_static", "strum", "strum_macros", + "threadpool", "toml", ] diff --git a/Cargo.toml b/Cargo.toml index 836cbb9..02f0ba3 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -12,6 +12,7 @@ strum = { version = "0.24", features = ["derive"] } lazy_static = "1.4.0" toml = "0.5.9" clap = {version = "4.1.6", features = ["derive"]} +threadpool = "1.8.1" [profile.release] panic = 'abort' diff --git a/src/craft.rs b/src/craft.rs index ed09088..80a65d1 100644 --- a/src/craft.rs +++ b/src/craft.rs @@ -6,8 +6,8 @@ use crate::specs::{Buff, BuffState, Recipe, Stats, Success}; #[derive(Clone)] pub struct Craft<'a> { - pub recipe: &'a Recipe, - pub stats: &'a Stats, + pub recipe: Recipe, + pub stats: Stats, pub buffs: BuffState, pub step_count: u32, pub durability: i32, @@ -20,7 +20,7 @@ pub struct Craft<'a> { } impl<'a> Craft<'a> { - pub fn new(recipe: &'a Recipe, stats: &'a Stats, depth: &'a u32) -> Craft<'a> { + pub fn new(recipe: Recipe, stats: Stats, depth: u32) -> Craft<'a> { Self { recipe, stats, @@ -32,7 +32,7 @@ impl<'a> Craft<'a> { cp: stats.max_cp as i32, success: Success::Pending, actions: Vec::new(), - depth: *depth, + depth: depth, } } diff --git a/src/main.rs b/src/main.rs index c48e37c..d7ce120 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,10 +1,12 @@ use crate::craft::Craft; use crate::solver::{generate_routes_phase1, generate_routes_phase2}; use crate::specs::{Recipe, Stats}; -use clap::Parser; -use std::thread; -use std::time::{Duration,Instant}; +use clap::Parser; +use std::sync::{Arc,Mutex}; +use std::time::{Instant}; +use threadpool::ThreadPool; + mod specs; pub mod action; @@ -33,6 +35,10 @@ struct Args { /// The depth of the first pass #[arg(short, long, default_value_t = 8)] depth: u32, + + /// Thread counts, default is 4 (can you even run ff with less ?) + #[arg(short, long, default_value_t = 4)] + threads: usize, } #[derive(Debug)] @@ -46,6 +52,7 @@ fn main() { let now = Instant::now(); + //read craft.toml let config: toml::Value = toml::from_str( &std::fs::read_to_string(&args.file_name) @@ -110,65 +117,69 @@ fn main() { }; let craft = Craft::new(recipe, stats, args.depth); + // Start a threadpool + let pool = ThreadPool::new(args.threads); + if args.verbose>0{ println!("Solving...\n"); println!("[P1] Starting phase 1..."); } let phase1_routes = generate_routes_phase1(craft); - if args.verbose>1{ + if args.verbose>0{ println!("[P1] Found {} routes, testing them all...",phase1_routes.len()); - for r in &phase1_routes{ - println!("[P1] {:?} p:{}% q:{}% c:{} d:{}", - r.actions, - r.progression * 100 / r.recipe.progress, - r.quality * 100 / r.recipe.quality, - r.cp, - r.durability, - ); - // println!("[P1] {}",r); - }; + if args.verbose>1{ + for r in &phase1_routes{ + println!("[P1] {:?} p:{}% q:{}% c:{} d:{}", + r.actions, + r.progression * 100 / r.recipe.progress, + r.quality * 100 / r.recipe.quality, + r.cp, + r.durability, + ); + // println!("[P1] {}",r); + }; + } } - // Core algorith, fill all found routes with the best route (doesn't branch, just replace) - let mut phase2_routes: Vec = Vec::new(); - // for route in phase1_routes { - // if let Some(route) = generate_routes_phase2(route) { - // phase2_routes.push(route); - // } - // } + // Core algorithm, fill all found routes with the best route (doesn't branch, just replace) + let arc_phase2_routes = Arc::new(Mutex::new(Vec::::new())); - let handle = thread::spawn(|| { - // for i in 1..10 { - // println!("hi number {} from the spawned thread!", i); - // thread::sleep(Duration::from_millis(1)); - // } - for route in phase1_routes { - /*if let Some(route) = */generate_routes_phase2(route); //{ - // phase2_routes.push(route); - //} - } - } - ); - - handle.join().unwrap(); + for route in phase1_routes { + let _phase2_routes = arc_phase2_routes.clone(); + pool.execute(move || { + if let Some(_route) = generate_routes_phase2(route){ + let mut shared = _phase2_routes.lock().unwrap(); + shared.push(_route); + }; + }); + } + pool.join(); + let phase2_routes = arc_phase2_routes.lock().unwrap(); + // Print the results if verbose - if args.verbose>1{ + if args.verbose>0{ println!("[P2] Found {} solutions, sorting",phase2_routes.len()); - for r in &phase2_routes{ - println!("[P2] {:?} p:{}% q:{}% d:{}", - r.actions, - r.progression * 100 / r.recipe.progress, - r.quality * 100 / r.recipe.quality, - r.durability); - }; + + if args.verbose>1{ + for r in phase2_routes.iter(){ + println!("[P2] {:?} p:{}% q:{}% d:{}", + r.actions, + r.progression * 100 / r.recipe.progress, + r.quality * 100 / r.recipe.quality, + r.durability); + }; + } } let top_route = match phase2_routes.iter().max_by_key(|route| route.quality) { Some(top) => top, - None => return, + None => { + println!("[P2] No route could finish the craft.\n[P2] Runtime {}ms. Now exiting...",now.elapsed().as_millis()); + return + }, }; @@ -201,8 +212,8 @@ fn main() { // Wait for enter println!(); - println!("Program finished sucessfuly in {}s and found {} solutions, [prog:{}]", - now.elapsed().as_secs(), + println!("Program finished sucessfuly in {}ms and found {} solutions, [prog:{}]", + now.elapsed().as_millis(), phase2_routes.len(), top_route.recipe.progress); println!("Press enter to exit..."); diff --git a/src/solver.rs b/src/solver.rs index 3019137..4608ada 100644 --- a/src/solver.rs +++ b/src/solver.rs @@ -149,11 +149,11 @@ pub fn next_action_phase_2<'a>(craft: &Craft) -> Vec> { final_actions } -pub fn generate_routes_phase2(craft: Craft) -> Option { +pub fn generate_routes_phase2<'a>(craft: Craft<'a>) -> Option> { let mut queue = VecDeque::new(); // println!("{}", ACTIONS.careful_synthesis.can_use(&craft)); - let mut top_route: Option = Some(craft.clone()); // Default route, no hq on that one + let mut top_route: Option> = Some(craft.clone()); // Default route, no hq on that one queue.push_back(craft);