Struct objc2_foundation::MainThreadBound
source · pub struct MainThreadBound<T>(/* private fields */);
NSThread
and dispatch
only.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>
impl<T> MainThreadBound<T>
Main functionality.
sourcepub fn new(inner: T, _mtm: MainThreadMarker) -> Self
pub fn new(inner: T, _mtm: MainThreadMarker) -> Self
Create a new MainThreadBound
value of type T
.
§Example
use objc2_foundation::{MainThreadMarker, MainThreadBound};
let foo;
let mtm = MainThreadMarker::new().expect("must be on the main thread");
let foo = MainThreadBound::new(foo, mtm);
// `foo` is now `Send + Sync`.
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>
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.