How to perform a parallel task in Rust?

Hello guys. i am new to rust. I'm building an Opengl application, I have OpenGL and glfw loading in the main thread.But I have a difficult task to calculate. I have a layout. and I need to calculate the positions of each node there.

To do this, I run a recursion and pass the current node and the parent node.The result I set in hashmap. and then recurse again and create a buffer based on positions from hashmap.It works great. How can I optimize part of the layout calculation.I need to create a thread and initialize the data there.I really stopped and do not know what to do. For example, a user intensively adds or removes new nodes. Then I need to get the absolute position for each node. This slow down the main thread.

// main thread

struct Bound { x: f32, y: f32, width: f32, height: f32 }

struct Layout { bounds: HashMap<usize, Bound>, nodes: stretch::node::Node }

impl Layout {
 fn calculate_layout() {
  /*
   get the position and insert 
   self.bounds.insert
   child = self.nodes.children();
   loop 
     self.calculate_layout child_node, parent
  */
 }
}

fn main() {
  let mut layout = Layout { bounds: HashMap::new(), nodes: /*...*/ }
  // Then I create a buffer based on the position
}

Is it possible to optimize it in some way ? How can I share data between the main thread and some x thread where I assume to perform the calculation process.

Use rayon for this. It can spawn tasks, and there's rayon::scope that makes recursion and memory management easy.

4 Likes