Reidar Sollid's Blog

Just another WordPress.com site

Introducing Rust Task

leave a comment »

So what is Rust then, from Wikipedia “Rust is an experimental, concurrent, multi-paradigm, compiled programming language developed by Mozilla Labs. It is designed to be practical, supporting pure-functional, concurrent-actor, imperative-procedural, and object-oriented styles.”
The most exiting thing for me is that it is influenced by Erlang and Limbo. Limbo with ports and channels and Erlang with the lightweight processes. I guess that Rust is designed with the purpose of writing web browser and to handle concurrency in a multi-core environment, these characteristics are well suited for backend systems as well.

In Rust we spawn out a new task, with the spawn keyword. This creates a lightweight process/task in which we can communicate with messages through channels. Default behavior for a variable in Rust is to be immutable, if you want a mutable variable you must explicitly declare it mutable with the mutable keyword.

So here is a little silly demo code of how to spawn a task and to send and receive messages from it.


use std;
import print = io:: println;

fn main() {
  let port = comm:: port::();
  let chan = comm:: chan::(port);
  do task:: spawn || {
    let result = compute_some();
    comm:: send(chan, result);
  }
  let first_result = compute_another();
  let second_result = comm::recv(port);
  print(#fmt("First, %s", first_result));
  print(#fmt("Second, %s", second_result));
}

fn compute_some() -> str {
  ret "Some computation";
}

fn compute_another() -> str {
  ret "Another computation";
}

I create two functions compute_some() and compute_another() in which only returns a string to recognize which function has been executed. Then in the main function I create a port and creates a channel connected to the port.Then I spawn out a task to compute where I execute the compute_some() function and sends the result on the channel.Then I execute one function and assign the result to a variable and then fetches the result from the channel and assigns it to a second variable. Then prints the result. Not very needy of concurrency here, but I guess you get the point.

For more on Rust Rust-lang I recommend the tutorial. Rust tutorail

Advertisements

Written by reidarsollid

June 24, 2012 at 9:16 pm

Posted in Rust, software

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: