pub struct MainThreadBound<T>(/* private fields */);Expand description
Make a type that can only be used on the main thread be Send + Sync.
On Drop, the inner type is sent to the main thread’s runloop and dropped
there. This may lead to deadlocks if the main runloop is not running, or
if it is waiting on a lock that the dropping thread is holding. See
run_on_main for some of the caveats around that.
§Related
This type takes inspiration from threadbound::ThreadBound.
The functionality also somewhat resembles Swift’s @MainActor, which
ensures that a type is only usable from the main thread.
Implementations§
Source§impl<T> MainThreadBound<T>
Main functionality.
impl<T> MainThreadBound<T>
Main functionality.
Sourcepub const fn new(inner: T, _mtm: MainThreadMarker) -> Self
pub const fn new(inner: T, _mtm: MainThreadMarker) -> Self
Create a new MainThreadBound value of type T.
§Example
use dispatch2::MainThreadBound;
use objc2::MainThreadMarker;
let foo;
let mtm = MainThreadMarker::new().expect("must be on the main thread");
let foo = MainThreadBound::new(foo, mtm);
// `foo` is now `Send + Sync`.Create a shared static that is only available from the main thread.
use core::cell::Cell;
use dispatch2::MainThreadBound;
use objc2::MainThreadMarker;
// Note: The destructor for this will never be run.
static SHARED: MainThreadBound<Cell<i32>> = MainThreadBound::new(
Cell::new(42),
// SAFETY: The MainThreadBound is created at `const`-time and put
// into a static, there is no thread associated with this, and
// hence no thread safety to worry about.
unsafe { MainThreadMarker::new_unchecked() },
);
let mtm = MainThreadMarker::new();
assert_eq!(SHARED.get(mtm).get(), 42);
SHARED.get(mtm).set(43);
assert_eq!(SHARED.get(mtm).get(), 43);Sourcepub fn get(&self, _mtm: MainThreadMarker) -> &T
pub fn get(&self, _mtm: MainThreadMarker) -> &T
Returns a reference to the value.
Sourcepub fn get_mut(&mut self, _mtm: MainThreadMarker) -> &mut T
pub fn get_mut(&mut self, _mtm: MainThreadMarker) -> &mut T
Returns a mutable reference to the value.
Sourcepub fn into_inner(self, _mtm: MainThreadMarker) -> T
pub fn into_inner(self, _mtm: MainThreadMarker) -> T
Extracts the value from the MainThreadBound container.
Source§impl<T> MainThreadBound<T>
Helper functions for running run_on_main.
impl<T> MainThreadBound<T>
Helper functions for running run_on_main.
Sourcepub fn get_on_main<F, R>(&self, f: F) -> R
pub fn get_on_main<F, R>(&self, f: F) -> R
Access the item on the main thread.
See run_on_main for caveats.
Sourcepub fn get_on_main_mut<F, R>(&mut self, f: F) -> R
pub fn get_on_main_mut<F, R>(&mut self, f: F) -> R
Access the item mutably on the main thread.
See run_on_main for caveats.