std::task::Wake - Rust
source link: https://doc.rust-lang.org/stable/std/task/trait.Wake.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
Trait std::task::Wake1.51.0[−][src]
The implementation of waking a task on an executor.
This trait can be used to create a Waker
. An executor can define an
implementation of this trait, and use that to construct a Waker to pass
to the tasks that are executed on that executor.
This trait is a memory-safe and ergonomic alternative to constructing a
RawWaker
. It supports the common executor design in which the data used
to wake up a task is stored in an Arc
. Some executors (especially
those for embedded systems) cannot use this API, which is why RawWaker
exists as an alternative for those systems.
Examples
A basic block_on
function that takes a future and runs it to completion on
the current thread.
Note: This example trades correctness for simplicity. In order to prevent
deadlocks, production-grade implementations will also need to handle
intermediate calls to thread::unpark
as well as nested invocations.
use std::future::Future; use std::sync::Arc; use std::task::{Context, Poll, Wake}; use std::thread::{self, Thread}; /// A waker that wakes up the current thread when called. struct ThreadWaker(Thread); impl Wake for ThreadWaker { fn wake(self: Arc<Self>) { self.0.unpark(); } } /// Run a future to completion on the current thread. fn block_on<T>(fut: impl Future<Output = T>) -> T { // Pin the future so it can be polled. let mut fut = Box::pin(fut); // Create a new context to be passed to the future. let t = thread::current(); let waker = Arc::new(ThreadWaker(t)).into(); let mut cx = Context::from_waker(&waker); // Run the future to completion. loop { match fut.as_mut().poll(&mut cx) { Poll::Ready(res) => return res, Poll::Pending => thread::park(), } } } block_on(async { println!("Hi from inside a future!"); });Run
Required methods
Provided methods
pub fn wake_by_ref(self: &Arc<Self>)
[src][−]
Implementors
Recommend
-
4
1.0.0[−][src]Module std::result[−]Er...
-
11
Variants Ready(T)[−]Represents that a value is immediately ready. Pending[−]Represents that a value is not read...
-
11
MILAN🦀 std::process::exit is evil - a Rust bug fixing story912 views•Jan 17...
-
10
Struct std::iter::Peekable1.0.0[...
-
7
Struct std::sync::Once1.0.0[−]
-
15
Trait std::io::Seek1.0.0[−]
-
6
Function std::panic::panic_any1.51.0...
-
7
impl<T, const N: usize> IntoIter<T, N>
-
4
pub macro ready($e:expr) { ... } Extracts the successful type of a Poll<T>. Thi...
-
0
Rust Project Reveals New 'Constitution' in Wake of Cri...
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK