DEV Community

El Bruno for Microsoft Azure

Posted on • Originally published at elbruno.com on

#Rust ๐Ÿฆ€- Working with threads ๐Ÿงต (concurrency)

Hi !

Working with threads is usually an interesting (challenging) task, when we program in low level languages. I love how easy is to do this in C# or Python, however, multi-threading in C++ is โ€ฆ a super fun moment.

So, the idea behind this is to have sections of code in our application runing in parallel to other sections of code.

And, with just 15 lines of code, we can see how easy is to do this in Rust.


use std::thread;
use std::time::Duration;

fn main() {
    thread::spawn(|| {
        println!(" >> Begin thread work, wait 2 seconds ...");
        thread::sleep(Duration::from_millis(2000));
        println!(" >> End thread work ...");
    });

    for i in 0..5 {
        println!("Loop 1 iteration: {}", i);
        thread::sleep(Duration::from_millis(500));
    }
}

Enter fullscreen mode Exit fullscreen mode

Our main thread will run a for loop, displaying a message every one second. And a secondary thread, will display a message, wait 2 seconds and then, show a 2nd message.

The output is similar to this one.


Loop 1 iteration: 0
  >> Begin thread work, wait 2 seconds ...
Loop 1 iteration: 1
Loop 1 iteration: 2
Loop 1 iteration: 3
  >> End thread work ...
Loop 1 iteration: 4

Enter fullscreen mode Exit fullscreen mode

Super easy !

I use the thread::spawn function to create a new thread. The spawn function takes a closure as a parameter, which defines code that should be executed by the thread.

In following posts, Iโ€™ll deep a little more in this sample.

Happy coding!

Greetings

El Bruno

More posts in my blog ElBruno.com.


Top comments (0)