Rust, Software Development

Create Threads That Work With Data in Rust

Photo by Mike from Pexels

Last Updated on

Rust allows us to create threads to run codes concurrently and work with data – access, return and modify using the move keyword.

Create Threads

We can create threads using the spawn function from the thread module. The function accepts a closure with no arguments. The closure can work with data. Consider the following codes that run a single thread. The thread only prints out a line of text 10 times before the main function completes.

Sample output from our lone thread.

We can create a number of threads and force the main function to wait until the threads finish. Consider the following codes.

Sample output from our threads. Note that the same result is not guaranteed after every re-run.

If we have a lot of threads running, it’s difficult to identify which thread does what operation. We could name them! The code snippet below names a thread “Process 001”, runs it, and displays its name.

The codes output the following.

Threads That Work With Data

If spawn accepts a closure which accepts 0 arguments, how do we pass data to and from a thread? We use variables created in another block inside the closure. Consider the following codes. We have 2 threads each using the display_vec function and a Vec instance. Notice that the Vec instances are declared and initialized outside of the closures but within the main function. Note that we need to use the move keyword with the closures.

This outputs

Output

To return values from threads, we pass closures that return data values. The code snippet below has a closure that returns 100.

We can also have threads that modify the values of its parameters and reflect the changes back to the calling codes. Check the codes below. In this case, we would want to modify a struct instance in a separate thread but display the same instance in the main thread.

This outputs

Tested using Rust 1.40.0.

You Might Also Like