-
Notifications
You must be signed in to change notification settings - Fork 0
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Fix implementation of Sync
for SpinLock
#1
Comments
This is confusing me because, I believe, if we share
|
I imagine a test for this would be:
#[test]
fn test_sync_bound() {
let other_data = std::sync::Mutex::new(Vec::new());
let m_guard = other_data.lock().unwrap();
let x = SpinLock::new(m_guard);
std::thread::scope(|s| {
s.spawn(|| x.lock().push(1));
s.spawn(|| {
let mut g = x.lock();
g.push(2);
g.push(2);
});
});
let g = x.lock();
assert!(g.as_slice() == [1, 2, 2] || g.as_slice() == [2, 2, 1]);
} But Miri was cool with that so maybe that test isn't validating what I hoped it would. It's good to note that |
Hmmm maybe I understand. Sync implies the type can be shared by two threads concurrently. Because of the lock, no two threads will have share the stored value concurrently. So we don’t need Sync. Send still feels wrong but I guess I’m maybe seeing why Sync is overkill. I feel like the lock is Sync if a reference to the inner data is Send… but that’s the same as Sync 😅Maybe the number of concurrent accessors is more important than the owner? That also doesn’t “feel” right… |
For tomorrow - https://stackoverflow.com/a/68708557 might clear some things up. |
Okay the vibe I'm getting is that, if a value of type
The docs say:
I used to think "transferring a type across thread boundaries" meant "transferring ownership of a type". Now I think it includes sending, for example, So, the situation with our
|
@andrewhalle brings up a good point - being able to send |
## This Commit Updates the bounds on `T` for `SpinLock` to implement `Sync`. This closes #1. ## Why? When reviewing my code and comparing it with the book's implementation, I noticed I had the incorrect bounds when implementing `Sync` for `SpinLock`. I had required `T: Sync` when the book had `T: Send`. I had erroneously thought that `Send` is only required when transferring owned values to other threads. See the comments in the issue for more details but I learned that `Send` is required to access `T`, `&T`, or `&mut T` _at all_ on another thread. `Sync` is _only_ required if concurrent access is required.
This reasoning:
rust_atomics_and_locks/src/spin_lock/mod.rs
Lines 37 to 40 in 8a5e3b7
is incorrect. The book mentions:
The text was updated successfully, but these errors were encountered: