0

Rust – Thread Examples

Rust supports the creation of threads to run code simultaneously.

std::thread

Threads are created and executed using the spawn function from the std::thread module.

Running Single Thread

Output

Running Multiple Threads

Output

Note: the same result is not guaranteed if the codes are ran again.

Named Thread

Output

Call Function with Parameters

This, however, will fail compilation when we try to display the contents of v1  and v2  in the main thread. To fix that, we would re-implement the codes this way:

This outputs

Output

Return Value from Thread

Output

Modify Instance within Thread

In this case, we would want to modify a struct instance in a separate thread but display the same instance in the main thread. When coming from other languages, the initial implementation we would think of is something like the following.

But this does not work and results to

To make this work, we would implement this way

This outputs

Tested using Rust 1.38.

Karl San Gabriel

Karl San Gabriel

Professional Software Developer