Concurrency in Rust

For a long time, it has not made sense to perform all tasks sequentially in a computer. Of course, sometimes you need to perform some tasks before others, but in most real-world applications, you will want to run some tasks in parallel.

You might, for example, want to respond to HTTP requests. If you do one after the other, the overall server will be slow. Especially when you get many requests per second and some of them take time to complete. You probably want to start responding to others before you finish with the current one.

Furthermore, we now have multiple processors in almost any computer or server, even in most mobile phones. This means that not only can we process other tasks in parallel while our main task is idle, we can really use one processor for each task by using threads. This is a feature that we must use to our advantage when developing high-performance applications.

The main issue with concurrency is that it's hard. We are not used to thinking in parallel, and as programmers we make mistakes. We only have to check some of the security vulnerabilities or bugs in our most-used systems, developed by the greatest programmers, to see that it's difficult to make it right.

Sometimes, we try to change a variable without remembering that another task might be reading it, or even changing it at the same time. Imagine a request counter in the HTTP example. If we separate the load between two processors, and each processor receives a request, the shared counter should go up by two, right?

Each thread wants to add 1 to the counter. For that, they load the current counter in the CPU, they add one to it and then save it again in the RAM. This takes some time, especially loading it from RAM, which means that if they both load the counter at the same time, they will both have the current counter in the CPU.

If both add one to the counter and save it back, the value in the RAM will only add one request, instead of two, because both processors will save the new +1 value in the RAM. This is what we call a data race. There are some tools that avoid this behavior, such as atomic variables, semaphores, and mutexes, but we sometimes forget to use them.

One of the best-known features in Rust is the fearless concurrency. This means that as long as we use safe Rust, we shouldn't be able to create a data race. This solves our issue but, how do they do it?

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.143.239.44