Skip to main content

Module sync

Module sync 

Source
Expand description

Shared state for a controller that runs on more than one thread.

The crate is single-threaded by construction, and that splits it in two. A device is one event loop, one RefCell per piece of state, and no atomics an MCU would have to pay for. A controller on a multi-threaded runtime is none of those things: it drives many nodes from a work-stealing pool, and a future that is !Send cannot be spawned there at all.

Shared is the seam. Without the sync-mutex feature it is a core::cell::RefCell and the controller stays single-threaded and cheap; with it, an RwLock, and the state becomes Send + Sync so a run future holding it can be spawned across threads.

ⓘ
use matter_kit::sync::Shared;

let fabrics = Shared::new(FabricTable::new());
// The same two lines compile either way.
let count = fabrics.borrow().len();
fabrics.borrow_mut().remove(index);

§One rule, and it is not optional

Never hold a borrow across an await.

That is the whole of it, in both builds, because RwLock is the shape core::cell::RefCell already has: many shared borrows, or one exclusive borrow. A Mutex would have one kind of lock, so two borrow()s would compile and work without the feature and deadlock with it — and a seam whose two builds disagree about what is legal is a seam that tests one of them.

What differs between the builds is only what happens when the rule is broken: a RefCell panics at the mistake, a lock waits somewhere else. Which is why the single-threaded build is the one to develop against.

The crate’s own device clusters deliberately keep their core::cell::RefCells: a device is single-threaded by construction and converting them would trade a panic that points at the mistake for a deadlock that does not.

Structs§

Sharedsync-mutex
State shared between the parts of a controller, across threads.

Type Aliases§

Refsync-mutex
A shared borrow of the contents.
RefMutsync-mutex
An exclusive borrow of the contents.