icerpc / slicec

The Slice compiler library
Apache License 2.0
13 stars 5 forks source link

Implement 'Send' and 'Sync' traits for our pointer types. #667

Closed InsertCreativityHere closed 10 months ago

InsertCreativityHere commented 10 months ago

This PR implements the Send and Sync trait for our 2 pointer types (OwnedPtr and WeakPtr).


These are 'marker' traits. Instead of requiring a type to implement some functions, they require the type to possess some intrinsic property. That's why these traits are marked 'unsafe'. It is up to the implementer to guarantee the conditions are upheld.

Send requires that transferring ownership of something between threads is safe. The pointed-to data lives on the heap, and doesn't care if the pointer moves between threads. All the state held by the pointers is private and local (they just hold a memory address and a TypeID). So, sending our pointers between threads is safe. As opposed to something like Rc, which holds a 'reference count' variable, whose value is shared between it's copies.

Sync requires that it's safe for 2 threads to simultaneously read from immutable references of your thing. The concern here is interior mutability, where you can mutate an object through an immutable reference. Unlike most pointers, ours do not use interior mutability. You need a mutable reference to a pointer to mutate it's data. So, it's safe for multiple threads to simultaneously have immutable access to our pointers. As opposed to RefCell, where 2 threads holding &RefCell could attempt to simultaneously mutate data, since RefCell allows for interior mutability.


Whether or not the AST (and all the grammar elements) should implement these traits is another question.