Skip to content

Instantly share code, notes, and snippets.

@bradurani
Created October 30, 2018 05:39
Show Gist options
  • Save bradurani/93f01d0f0d3311e35d46b9039f43c3c4 to your computer and use it in GitHub Desktop.
Save bradurani/93f01d0f0d3311e35d46b9039f43c3c4 to your computer and use it in GitHub Desktop.
Recursive Multi-Threaded Mutating Tree Search
use std::thread;
use std::thread::JoinHandle;
use std::sync::{Arc, Mutex, MutexGuard};
type Node = Arc<Mutex<TreeNode>>;
#[derive(Debug)]
struct TreeNode {
value: u16,
children: Vec<Node>,
}
fn main() {
let mut root = TreeNode {
value: 1,
children: vec![Arc::new(Mutex::new(TreeNode{
value:2,
children: vec![]
}))],
};
for _i in 1..5 {
let temp = root;
root = find_best_child(temp);
println!("{:#?}", root);
}
}
fn find_best_child(root: TreeNode) -> TreeNode {
let new_children = mutate_and_add_children(root.children);
new_children.into_iter().map(|c| Arc::try_unwrap(c).expect("unwraping arc").into_inner().expect("unwrapping mutex"))
.max_by_key(|c| { println!("c {:?}", c); c.value }).expect("max by")
}
fn mutate_and_add_children(children: Vec<Node>) -> Vec<Node>{
children.into_iter()
.map(|child| {
thread(child.clone())
}).map(|th| th.join().expect("panicked joining threads"))
.collect()
}
fn thread(child: Node) -> JoinHandle<Node> {
thread::spawn(move || {
let child_guard = child.lock().unwrap();
mutate(child_guard);
child.clone()
})
}
fn mutate(mut child: MutexGuard<TreeNode>){
for _i in 1..5 {
child.children.push(Arc::new(Mutex::new(TreeNode {
value: rand::random(),
children: vec![Arc::new(Mutex::new(TreeNode {
value: rand::random(),
children: vec![]
}))]
})));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment