The Send trait

A structure implementing the Send trait is safe to be moved between threads. This means that you can safely transfer ownership of a Send type between threads. The standard library implements Send for the types that can actually be moved across thread boundaries, and the compiler will automatically implement it for your types if they can also be moved between threads. If a type is only composed of Send types, it will be a Send type.

Most types in the standard library implement the Send trait. You can safely move ownership of a u32 to another thread, for example. This means that the previous thread will not be able to use it again and that the new thread will be in charge of dropping it once it gets out of scope.

There are some exceptions, though. Raw pointers cannot be safely moved to another thread, since they have no safety guards. You can copy a raw pointer multiple times, and it could happen that one gets to one thread and the other stays in the current one. If both try to manipulate the same memory at the same time, it will create undefined behavior.

The other exception is the reference-counted pointer or Rc type. This type can easily and efficiently create shared pointers to a given memory location. It will be safe since the type itself has some memory guarantees to make sure that if a mutable borrow exists, no other borrows can be made, and that if one or more non-mutable borrows exists, no mutable borrow can be made. The information pointed by the pointer will be dropped at the same time the last reference gets out of scope.

This works by having a counter that adds 1 each time a reference gets created by calling the clone() method and that subtracts 1 once a reference gets dropped. You might have already realized the issue that will arise when sharing it between threads: if two threads drop a reference at the same time, the reference count might only subtract 1. This means that when the last reference gets dropped, the counter won't be zero, and it will not drop the Rc, creating a memory leak.

Since Rust cannot allow memory leaks, the Rc type is not Send. There is an equivalent shared pointer that can be shared between threads, the atomically reference-counted pointer or Arc. This type makes sure that each addition or subtraction to the reference count gets performed atomically, so that if a new thread wants to add or subtract one reference, it will need to wait for the other threads to finish updating that counter. This makes it thread-safe, but it will be slower than an Rc due to the checks that need to be performed. So, you should use Rc if you don't need to send a reference to another thread.

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

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