Lecture Note 8

- Send trait (unsafe trait)
- Sync trait : T is Sync iff &T is Send
- sync is guaranteed when we can send the borrwo to the other thread
- Arc
```rust
Arc
- before sending the Arc<T>, copying arc happens
- sync: accessing the reference of the value from multiple threads
- sendableness is propagated without the types
- Sync + Send impl'ed for Arc<T>
```rust
pub trait RawLock: Default + Send + Sync { // send for accessing borrow from other threads/ glob scope
type Token;
fn lock(&self) -> Self::Token;
unsafe fn unlock(&self, token: Self::Token);
// this unsafe marker means that the programmer should use this with caution:
// not necessarily using unsafe function calls inside the implementation
}
pub trait RawTryLock: RawLock {
fn try_lock(&self) -> Result<Self::Token, ()>;
}
- T1 -> has
&mut T
- T2 (scoped thread) -> has
&mut T
: t1’s mut ref is temporarily deactivates -
after joining T2, T1’s mut ref is alive again!
- backpressure!
- we should cut out some of the hight-cost requests
// send and sync is unsafe! -> this is why impl is marked unsafe (warning programmers)
unsafe impl<L: RawLock, T: Send> Sync for Lock<L, T> {
underlying object is sent to other traits : we need send for the parameter (doesnt' care whether it's sync)
we can guarantee that the lock is never accessed / modified at the same time
}
- Introducing cells A xor M principle (alias xor modify)
Lock + Data combined
-> used by several threads (only exclusively by maximum one thread)
-> introducing unsafecell
Lock + unsafecell<Data> getting/using &mut D from another threads
pub const fn get(&self) -> *mut T