#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));
    }
}

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

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.

More info in https://beacons.ai/elbruno


Advertisement

Leave a comment

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 )

Facebook photo

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

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: