Clarify Send-Sync relationship (#237)

This commit is contained in:
Luca Palmieri 2024-12-18 17:22:16 +01:00 committed by GitHub
parent cc0092b2c6
commit fb19005d5f
No known key found for this signature in database
GPG key ID: B5690EEEBB952194

View file

@ -5,20 +5,20 @@ Before we wrap up this chapter, let's talk about another key trait in Rust's sta
`Sync` is an auto trait, just like `Send`.\ `Sync` is an auto trait, just like `Send`.\
It is automatically implemented by all types that can be safely **shared** between threads. It is automatically implemented by all types that can be safely **shared** between threads.
In order words: `T: Sync` means that `&T` is `Send`. In order words: `T` is Sync if `&T` is `Send`.
## `Sync` doesn't imply `Send` ## `T: Sync` doesn't imply `T: Send`
It's important to note that `Sync` doesn't imply `Send`.\ It's important to note that `T` can be `Sync` without being `Send`.\
For example: `MutexGuard` is not `Send`, but it is `Sync`. For example: `MutexGuard` is not `Send`, but it is `Sync`.
It isn't `Send` because the lock must be released on the same thread that acquired it, therefore we don't It isn't `Send` because the lock must be released on the same thread that acquired it, therefore we don't
want `MutexGuard` to be dropped on a different thread.\ want `MutexGuard` to be dropped on a different thread.\
But it is `Sync`, because giving a `&MutexGuard` to another thread has no impact on where the lock is released. But it is `Sync`, because giving a `&MutexGuard` to another thread has no impact on where the lock is released.
## `Send` doesn't imply `Sync` ## `T: Send` doesn't imply `T: Sync`
The opposite is also true: `Send` doesn't imply `Sync`.\ The opposite is also true: `T` can be `Send` without being `Sync`.\
For example: `RefCell<T>` is `Send` (if `T` is `Send`), but it is not `Sync`. For example: `RefCell<T>` is `Send` (if `T` is `Send`), but it is not `Sync`.
`RefCell<T>` performs runtime borrow checking, but the counters it uses to track borrows are not thread-safe. `RefCell<T>` performs runtime borrow checking, but the counters it uses to track borrows are not thread-safe.