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

Output

Return Value from Thread

Output

Modify Variable Value within Thread

When we have a variable with a longer scope than the thread, modifying that within a thread causes the following compile-time error:

For example

To fix this, we have to use the move  keyword.

Tested using Rust 1.38.

Karl San Gabriel

Karl San Gabriel

Professional Software Developer