threadcell

A cell whose value can only be accessed by a owning thread

18 releases (4 stable)

1.0.3 May 5, 2023
1.0.0 Apr 20, 2023
0.12.0 Mar 20, 2023
0.8.2 Dec 11, 2022
0.8.1 Sep 13, 2022

#322 in Concurrency

Download history 20/week @ 2024-07-20 121/week @ 2024-07-27 36/week @ 2024-08-03 21/week @ 2024-08-10 61/week @ 2024-08-17 24/week @ 2024-08-24 6/week @ 2024-08-31 6/week @ 2024-09-21 7/week @ 2024-09-28 8/week @ 2024-10-05 10/week @ 2024-10-12 30/week @ 2024-10-19 17/week @ 2024-10-26 13/week @ 2024-11-02

71 downloads per month
Used in onsen

MIT/Apache

27KB
420 lines

A cell whose value can only be accessed by a owning thread. Much like a Mutex but without blocking locks. Access to ThreadCells is passed cooperatively between threads.

Semantics

ThreadCell

A ThreadCell and references therof can always be send to other threads

  • A ThreadCell that is owned by a thread then only that thread can:
    • Access its value
    • Drop the cell.
    • Set the Cell into a disowned state.
  • On a ThreadCell that is disowned any thread can:
    • Take ownership of it
    • Drop it

Threads that do not own a ThreadCell and access its value will panic. There are 'try_*' variants in the API that will not panic but return a bool or Option instead.

Api

There are two variants how Threadcells can be used. From 'v0.11' on these are mutually exclusive.

Acquire/Release

Offers manual control over a ThreadCell ownership. The disadvantage here is that when a thread holding a ThreadCell will panic, this cell stays owned by the dead thread. One either needs to discover these cases and then steal() the cell or use that only in cases where panics are impossible or aborting the whole process. This API can be used to implement custom guard types as well.

Guard

threadcell::Guard and threadcell::GuardMut are handle proper acquire/release for threadcells. There can be only one guard active per threadcell. As long a thread has a Guard the threadcell is owned by that thread and will be released when the Guard becomes dropped.

Guards implement Deref and DerefMut making accessing threadcells more ergonomic.

Use Cases

  • Single threaded applications that need a static mutable global variable can use ThreadCell<RefCell<T>>.
  • A static mut ThreadCell<T> will needs unsafe code but is actually safe because ThreadCell guards against concurrent access.
  • Sharing data between threads where synchronizaton is done out of band with other syncronization primitives.

Dependencies