Wednesday 13 May 2015

Rust: start thread & return value on finish

Rust threads are relatively easy to spawn and pass results back from.

use std::thread;

pub fn add_in_future(i1: i32, i2: i32) -> i32 {
  let handle = thread::spawn(move || {
    i1 + i2

mod test {
  use super::*;

  fn test_future() {
    let expected = 3;
    let actual = add_in_future(1, 2);
    assert_eq!(expected, actual);

The add_in_future function sums two numbers in a separate thread. Then the originating thread consumes the result. The move keyword moves ownership of variables to the new thread.

This post is just a code snippet written by someone getting started. No promises are made about code quality. Version: rustc 1.0.0-beta.4 (850151a75 2015-04-30) (built 2015-04-30)

No comments:

Post a Comment

All comments are moderated