If you find this helpful, please like, bookmark, and follow. To keep learning along, follow this series.
16.4.1 Send and Sync Traits
Rust itself has relatively few concurrency features. The concurrency features mentioned so far come from the standard library rather than the language itself. In fact, you do not need to limit yourself to the standard library—you can implement concurrency yourself.
There are two concurrency concepts in Rust:
-
std::marker::Synctrait -
std::marker::Sendtrait
These two traits are called marker traits because they do not define any methods; they only mark properties.
16.4.2 Send: Allowing Ownership Transfer Between Threads
In the previous article, we tried to pass Rc<T> across threads and failed because it does not implement the Send trait.
In Rust, almost all types implement Send. Aside from raw pointers, almost all primitive types implement the Send trait. But Rc<T> does not implement Send; it can only be used in single-threaded scenarios.
Any type composed entirely of Send types is also marked as Send, which is equivalent to implementing the Send trait.
16.4.3 Sync: Allowing Access From Multiple Threads
Types that implement Sync can be safely referenced by multiple threads. In other words, if T implements Sync, then &T implements Send.
Primitive types all implement Sync. Any type composed entirely of Sync types is also equivalent to Sync. However, Rc<T> is not Sync, and the RefCell<T> and Cell<T> families are not Sync either, while Mutex<T> is Sync.
16.4.4 Manually Implementing Send and Sync Is Unsafe
Because types composed of Send and Sync parts automatically inherit Send and Sync, we do not need to implement these traits manually. As marker traits, they do not even have any methods to implement. They are only used to enforce concurrency-related invariants.
Manually implementing these traits involves writing unsafe Rust code. We will discuss unsafe Rust in later articles (for this topic, see The Rustonomicon); for now, the important point is that when building new concurrent types, the Send and Sync components need to be considered carefully to preserve safety guarantees.
In one sentence: do not try to implement Send and Sync manually!!!
Top comments (0)