This month’s instalment of our ongoing Rust series will cover concurrent programming. The difficulty with concurrency can be summed up as “Shared Mutable State is the root of all problems”. However, Rust takes a different approach towards concurrency. Instead of dealing with the mutable part, Rust deals with the shared part. Put simply, the Rust compiler will let you know about any errors in the “shared” part; therefore, if your Rust code compiles you have no such errors. As a result, it’s okay to have shared memory among threads in Rust.
So, it’s in concurrent programming that you might appreciate all the Rust rules regarding borrowing, ownership and mutability. To get us going we’ll present a simple concurrent Rust program that’s far from perfect.
Basic concurrency
Rust starts a new thread using the thread::spawn() function that’s part of the std::thread module. The core code of simple.rs is the following:
Two things are happening here. First, there’s a for loop used for calling thread::spawn() five times and therefore creating five threads. Second, there’s a call to thread::sleep() for delaying the termination of the thread. Threads usually don’t just print messages, but perform actual work that takes time. Let’s now run simple.rs, which generates the following output:
Start.
End.
First, bear in mind that there are two println!() statements before and after the for loop, which is the reason for the two lines of output. But where are the messages from the five threads? It looks like doesn’t behave as expected. The messages from