some minor formatting updates
This commit is contained in:
@@ -1,5 +1,5 @@
|
||||
<!DOCTYPE HTML>
|
||||
<html lang="en" class="sidebar-visible no-js">
|
||||
<html lang="en" class="sidebar-visible no-js light">
|
||||
<head>
|
||||
<!-- Book generated using mdBook -->
|
||||
<meta charset="UTF-8">
|
||||
@@ -32,11 +32,11 @@
|
||||
|
||||
|
||||
</head>
|
||||
<body class="light">
|
||||
<body>
|
||||
<!-- Provide site root to javascript -->
|
||||
<script type="text/javascript">
|
||||
var path_to_root = "";
|
||||
var default_theme = "light";
|
||||
var default_theme = window.matchMedia("(prefers-color-scheme: dark)").matches ? "light" : "light";
|
||||
</script>
|
||||
|
||||
<!-- Work around some values being stored in localStorage wrapped in quotes -->
|
||||
@@ -60,8 +60,11 @@
|
||||
var theme;
|
||||
try { theme = localStorage.getItem('mdbook-theme'); } catch(e) { }
|
||||
if (theme === null || theme === undefined) { theme = default_theme; }
|
||||
document.body.className = theme;
|
||||
document.querySelector('html').className = theme + ' js';
|
||||
var html = document.querySelector('html');
|
||||
html.classList.remove('no-js')
|
||||
html.classList.remove('light')
|
||||
html.classList.add(theme);
|
||||
html.classList.add('js');
|
||||
</script>
|
||||
|
||||
<!-- Hide / unhide sidebar before it is displayed -->
|
||||
@@ -77,8 +80,8 @@
|
||||
</script>
|
||||
|
||||
<nav id="sidebar" class="sidebar" aria-label="Table of contents">
|
||||
<div class="sidebar-scrollbox">
|
||||
<ol class="chapter"><li class="affix"><a href="introduction.html">Introduction</a></li><li><a href="0_background_information.html"><strong aria-hidden="true">1.</strong> Background information</a></li><li><a href="1_futures_in_rust.html"><strong aria-hidden="true">2.</strong> Futures in Rust</a></li><li><a href="2_waker_context.html"><strong aria-hidden="true">3.</strong> Waker and Context</a></li><li><a href="3_generators_async_await.html"><strong aria-hidden="true">4.</strong> Generators and async/await</a></li><li><a href="4_pin.html"><strong aria-hidden="true">5.</strong> Pin</a></li><li><a href="6_future_example.html" class="active"><strong aria-hidden="true">6.</strong> Implementing Futures</a></li><li><a href="8_finished_example.html"><strong aria-hidden="true">7.</strong> Finished example (editable)</a></li><li class="affix"><a href="conclusion.html">Conclusion and exercises</a></li></ol>
|
||||
<div id="sidebar-scrollbox" class="sidebar-scrollbox">
|
||||
<ol class="chapter"><li class="expanded affix "><a href="introduction.html">Introduction</a></li><li class="expanded "><a href="0_background_information.html"><strong aria-hidden="true">1.</strong> Background information</a></li><li class="expanded "><a href="1_futures_in_rust.html"><strong aria-hidden="true">2.</strong> Futures in Rust</a></li><li class="expanded "><a href="2_waker_context.html"><strong aria-hidden="true">3.</strong> Waker and Context</a></li><li class="expanded "><a href="3_generators_async_await.html"><strong aria-hidden="true">4.</strong> Generators and async/await</a></li><li class="expanded "><a href="4_pin.html"><strong aria-hidden="true">5.</strong> Pin</a></li><li class="expanded "><a href="6_future_example.html" class="active"><strong aria-hidden="true">6.</strong> Implementing Futures</a></li><li class="expanded "><a href="8_finished_example.html"><strong aria-hidden="true">7.</strong> Finished example (editable)</a></li><li class="expanded affix "><a href="conclusion.html">Conclusion and exercises</a></li></ol>
|
||||
</div>
|
||||
<div id="sidebar-resize-handle" class="sidebar-resize-handle"></div>
|
||||
</nav>
|
||||
@@ -149,7 +152,7 @@
|
||||
|
||||
<div id="content" class="content">
|
||||
<main>
|
||||
<h1><a class="header" href="#futures-in-rust" id="futures-in-rust">Futures in Rust</a></h1>
|
||||
<h1><a class="header" href="#implementing-futures---main-example" id="implementing-futures---main-example">Implementing Futures - main example</a></h1>
|
||||
<p>We'll create our own <code>Futures</code> together with a fake reactor and a simple
|
||||
executor which allows you to edit, run an play around with the code right here
|
||||
in your browser.</p>
|
||||
@@ -540,13 +543,13 @@ and make it sleep for some time which we specify when we create a <code>Task</co
|
||||
of seconds here, just give it some time to run.</p>
|
||||
<p>In the last chapter we have the <a href="./8_finished_example.html">whole 200 lines in an editable window</a>
|
||||
which you can edit and change the way you like.</p>
|
||||
<pre><pre class="playpen"><code class="language-rust edition2018"># use std::{
|
||||
# future::Future, pin::Pin, sync::{mpsc::{channel, Sender}, Arc, Mutex},
|
||||
# task::{Context, Poll, RawWaker, RawWakerVTable, Waker},
|
||||
# thread::{self, JoinHandle}, time::{Duration, Instant}
|
||||
# };
|
||||
#
|
||||
fn main() {
|
||||
<pre><pre class="playpen"><code class="language-rust edition2018"><span class="boring">use std::{
|
||||
</span><span class="boring"> future::Future, pin::Pin, sync::{mpsc::{channel, Sender}, Arc, Mutex},
|
||||
</span><span class="boring"> task::{Context, Poll, RawWaker, RawWakerVTable, Waker},
|
||||
</span><span class="boring"> thread::{self, JoinHandle}, time::{Duration, Instant}
|
||||
</span><span class="boring">};
|
||||
</span><span class="boring">
|
||||
</span>fn main() {
|
||||
// This is just to make it easier for us to see when our Future was resolved
|
||||
let start = Instant::now();
|
||||
|
||||
@@ -594,162 +597,162 @@ fn main() {
|
||||
reactor.lock().map(|mut r| r.close()).unwrap();
|
||||
}
|
||||
|
||||
# // ============================= EXECUTOR ====================================
|
||||
# fn block_on<F: Future>(mut future: F) -> F::Output {
|
||||
# let mywaker = Arc::new(MyWaker{ thread: thread::current() });
|
||||
# let waker = waker_into_waker(Arc::into_raw(mywaker));
|
||||
# let mut cx = Context::from_waker(&waker);
|
||||
# let val = loop {
|
||||
# let pinned = unsafe { Pin::new_unchecked(&mut future) };
|
||||
# match Future::poll(pinned, &mut cx) {
|
||||
# Poll::Ready(val) => break val,
|
||||
# Poll::Pending => thread::park(),
|
||||
# };
|
||||
# };
|
||||
# val
|
||||
# }
|
||||
#
|
||||
# // ====================== FUTURE IMPLEMENTATION ==============================
|
||||
# #[derive(Clone)]
|
||||
# struct MyWaker {
|
||||
# thread: thread::Thread,
|
||||
# }
|
||||
#
|
||||
# #[derive(Clone)]
|
||||
# pub struct Task {
|
||||
# id: usize,
|
||||
# reactor: Arc<Mutex<Reactor>>,
|
||||
# data: u64,
|
||||
# is_registered: bool,
|
||||
# }
|
||||
#
|
||||
# fn mywaker_wake(s: &MyWaker) {
|
||||
# let waker_ptr: *const MyWaker = s;
|
||||
# let waker_arc = unsafe {Arc::from_raw(waker_ptr)};
|
||||
# waker_arc.thread.unpark();
|
||||
# }
|
||||
#
|
||||
# fn mywaker_clone(s: &MyWaker) -> RawWaker {
|
||||
# let arc = unsafe { Arc::from_raw(s).clone() };
|
||||
# std::mem::forget(arc.clone()); // increase ref count
|
||||
# RawWaker::new(Arc::into_raw(arc) as *const (), &VTABLE)
|
||||
# }
|
||||
#
|
||||
# const VTABLE: RawWakerVTable = unsafe {
|
||||
# RawWakerVTable::new(
|
||||
# |s| mywaker_clone(&*(s as *const MyWaker)), // clone
|
||||
# |s| mywaker_wake(&*(s as *const MyWaker)), // wake
|
||||
# |s| mywaker_wake(*(s as *const &MyWaker)), // wake by ref
|
||||
# |s| drop(Arc::from_raw(s as *const MyWaker)), // decrease refcount
|
||||
# )
|
||||
# };
|
||||
#
|
||||
# fn waker_into_waker(s: *const MyWaker) -> Waker {
|
||||
# let raw_waker = RawWaker::new(s as *const (), &VTABLE);
|
||||
# unsafe { Waker::from_raw(raw_waker) }
|
||||
# }
|
||||
#
|
||||
# impl Task {
|
||||
# fn new(reactor: Arc<Mutex<Reactor>>, data: u64, id: usize) -> Self {
|
||||
# Task {
|
||||
# id,
|
||||
# reactor,
|
||||
# data,
|
||||
# is_registered: false,
|
||||
# }
|
||||
# }
|
||||
# }
|
||||
#
|
||||
# impl Future for Task {
|
||||
# type Output = usize;
|
||||
# fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
|
||||
# let mut r = self.reactor.lock().unwrap();
|
||||
# if r.is_ready(self.id) {
|
||||
# Poll::Ready(self.id)
|
||||
# } else if self.is_registered {
|
||||
# Poll::Pending
|
||||
# } else {
|
||||
# r.register(self.data, cx.waker().clone(), self.id);
|
||||
# drop(r);
|
||||
# self.is_registered = true;
|
||||
# Poll::Pending
|
||||
# }
|
||||
# }
|
||||
# }
|
||||
#
|
||||
# // =============================== REACTOR ===================================
|
||||
# struct Reactor {
|
||||
# dispatcher: Sender<Event>,
|
||||
# handle: Option<JoinHandle<()>>,
|
||||
# readylist: Arc<Mutex<Vec<usize>>>,
|
||||
# }
|
||||
# #[derive(Debug)]
|
||||
# enum Event {
|
||||
# Close,
|
||||
# Timeout(Waker, u64, usize),
|
||||
# }
|
||||
#
|
||||
# impl Reactor {
|
||||
# fn new() -> Self {
|
||||
# let (tx, rx) = channel::<Event>();
|
||||
# let readylist = Arc::new(Mutex::new(vec![]));
|
||||
# let rl_clone = readylist.clone();
|
||||
# let mut handles = vec![];
|
||||
# let handle = thread::spawn(move || {
|
||||
# // This simulates some I/O resource
|
||||
# for event in rx {
|
||||
# println!("REACTOR: {:?}", event);
|
||||
# let rl_clone = rl_clone.clone();
|
||||
# match event {
|
||||
# Event::Close => break,
|
||||
# Event::Timeout(waker, duration, id) => {
|
||||
# let event_handle = thread::spawn(move || {
|
||||
# thread::sleep(Duration::from_secs(duration));
|
||||
# rl_clone.lock().map(|mut rl| rl.push(id)).unwrap();
|
||||
# waker.wake();
|
||||
# });
|
||||
#
|
||||
# handles.push(event_handle);
|
||||
# }
|
||||
# }
|
||||
# }
|
||||
#
|
||||
# for handle in handles {
|
||||
# handle.join().unwrap();
|
||||
# }
|
||||
# });
|
||||
#
|
||||
# Reactor {
|
||||
# readylist,
|
||||
# dispatcher: tx,
|
||||
# handle: Some(handle),
|
||||
# }
|
||||
# }
|
||||
#
|
||||
# fn register(&mut self, duration: u64, waker: Waker, data: usize) {
|
||||
# self.dispatcher
|
||||
# .send(Event::Timeout(waker, duration, data))
|
||||
# .unwrap();
|
||||
# }
|
||||
#
|
||||
# fn close(&mut self) {
|
||||
# self.dispatcher.send(Event::Close).unwrap();
|
||||
# }
|
||||
#
|
||||
# fn is_ready(&self, id_to_check: usize) -> bool {
|
||||
# self.readylist
|
||||
# .lock()
|
||||
# .map(|rl| rl.iter().any(|id| *id == id_to_check))
|
||||
# .unwrap()
|
||||
# }
|
||||
# }
|
||||
#
|
||||
# impl Drop for Reactor {
|
||||
# fn drop(&mut self) {
|
||||
# self.handle.take().map(|h| h.join().unwrap()).unwrap();
|
||||
# }
|
||||
# }
|
||||
</code></pre></pre>
|
||||
<span class="boring">// ============================= EXECUTOR ====================================
|
||||
</span><span class="boring">fn block_on<F: Future>(mut future: F) -> F::Output {
|
||||
</span><span class="boring"> let mywaker = Arc::new(MyWaker{ thread: thread::current() });
|
||||
</span><span class="boring"> let waker = waker_into_waker(Arc::into_raw(mywaker));
|
||||
</span><span class="boring"> let mut cx = Context::from_waker(&waker);
|
||||
</span><span class="boring"> let val = loop {
|
||||
</span><span class="boring"> let pinned = unsafe { Pin::new_unchecked(&mut future) };
|
||||
</span><span class="boring"> match Future::poll(pinned, &mut cx) {
|
||||
</span><span class="boring"> Poll::Ready(val) => break val,
|
||||
</span><span class="boring"> Poll::Pending => thread::park(),
|
||||
</span><span class="boring"> };
|
||||
</span><span class="boring"> };
|
||||
</span><span class="boring"> val
|
||||
</span><span class="boring">}
|
||||
</span><span class="boring">
|
||||
</span><span class="boring">// ====================== FUTURE IMPLEMENTATION ==============================
|
||||
</span><span class="boring">#[derive(Clone)]
|
||||
</span><span class="boring">struct MyWaker {
|
||||
</span><span class="boring"> thread: thread::Thread,
|
||||
</span><span class="boring">}
|
||||
</span><span class="boring">
|
||||
</span><span class="boring">#[derive(Clone)]
|
||||
</span><span class="boring">pub struct Task {
|
||||
</span><span class="boring"> id: usize,
|
||||
</span><span class="boring"> reactor: Arc<Mutex<Reactor>>,
|
||||
</span><span class="boring"> data: u64,
|
||||
</span><span class="boring"> is_registered: bool,
|
||||
</span><span class="boring">}
|
||||
</span><span class="boring">
|
||||
</span><span class="boring">fn mywaker_wake(s: &MyWaker) {
|
||||
</span><span class="boring"> let waker_ptr: *const MyWaker = s;
|
||||
</span><span class="boring"> let waker_arc = unsafe {Arc::from_raw(waker_ptr)};
|
||||
</span><span class="boring"> waker_arc.thread.unpark();
|
||||
</span><span class="boring">}
|
||||
</span><span class="boring">
|
||||
</span><span class="boring">fn mywaker_clone(s: &MyWaker) -> RawWaker {
|
||||
</span><span class="boring"> let arc = unsafe { Arc::from_raw(s).clone() };
|
||||
</span><span class="boring"> std::mem::forget(arc.clone()); // increase ref count
|
||||
</span><span class="boring"> RawWaker::new(Arc::into_raw(arc) as *const (), &VTABLE)
|
||||
</span><span class="boring">}
|
||||
</span><span class="boring">
|
||||
</span><span class="boring">const VTABLE: RawWakerVTable = unsafe {
|
||||
</span><span class="boring"> RawWakerVTable::new(
|
||||
</span><span class="boring"> |s| mywaker_clone(&*(s as *const MyWaker)), // clone
|
||||
</span><span class="boring"> |s| mywaker_wake(&*(s as *const MyWaker)), // wake
|
||||
</span><span class="boring"> |s| mywaker_wake(*(s as *const &MyWaker)), // wake by ref
|
||||
</span><span class="boring"> |s| drop(Arc::from_raw(s as *const MyWaker)), // decrease refcount
|
||||
</span><span class="boring"> )
|
||||
</span><span class="boring">};
|
||||
</span><span class="boring">
|
||||
</span><span class="boring">fn waker_into_waker(s: *const MyWaker) -> Waker {
|
||||
</span><span class="boring"> let raw_waker = RawWaker::new(s as *const (), &VTABLE);
|
||||
</span><span class="boring"> unsafe { Waker::from_raw(raw_waker) }
|
||||
</span><span class="boring">}
|
||||
</span><span class="boring">
|
||||
</span><span class="boring">impl Task {
|
||||
</span><span class="boring"> fn new(reactor: Arc<Mutex<Reactor>>, data: u64, id: usize) -> Self {
|
||||
</span><span class="boring"> Task {
|
||||
</span><span class="boring"> id,
|
||||
</span><span class="boring"> reactor,
|
||||
</span><span class="boring"> data,
|
||||
</span><span class="boring"> is_registered: false,
|
||||
</span><span class="boring"> }
|
||||
</span><span class="boring"> }
|
||||
</span><span class="boring">}
|
||||
</span><span class="boring">
|
||||
</span><span class="boring">impl Future for Task {
|
||||
</span><span class="boring"> type Output = usize;
|
||||
</span><span class="boring"> fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
|
||||
</span><span class="boring"> let mut r = self.reactor.lock().unwrap();
|
||||
</span><span class="boring"> if r.is_ready(self.id) {
|
||||
</span><span class="boring"> Poll::Ready(self.id)
|
||||
</span><span class="boring"> } else if self.is_registered {
|
||||
</span><span class="boring"> Poll::Pending
|
||||
</span><span class="boring"> } else {
|
||||
</span><span class="boring"> r.register(self.data, cx.waker().clone(), self.id);
|
||||
</span><span class="boring"> drop(r);
|
||||
</span><span class="boring"> self.is_registered = true;
|
||||
</span><span class="boring"> Poll::Pending
|
||||
</span><span class="boring"> }
|
||||
</span><span class="boring"> }
|
||||
</span><span class="boring">}
|
||||
</span><span class="boring">
|
||||
</span><span class="boring">// =============================== REACTOR ===================================
|
||||
</span><span class="boring">struct Reactor {
|
||||
</span><span class="boring"> dispatcher: Sender<Event>,
|
||||
</span><span class="boring"> handle: Option<JoinHandle<()>>,
|
||||
</span><span class="boring"> readylist: Arc<Mutex<Vec<usize>>>,
|
||||
</span><span class="boring">}
|
||||
</span><span class="boring">#[derive(Debug)]
|
||||
</span><span class="boring">enum Event {
|
||||
</span><span class="boring"> Close,
|
||||
</span><span class="boring"> Timeout(Waker, u64, usize),
|
||||
</span><span class="boring">}
|
||||
</span><span class="boring">
|
||||
</span><span class="boring">impl Reactor {
|
||||
</span><span class="boring"> fn new() -> Self {
|
||||
</span><span class="boring"> let (tx, rx) = channel::<Event>();
|
||||
</span><span class="boring"> let readylist = Arc::new(Mutex::new(vec![]));
|
||||
</span><span class="boring"> let rl_clone = readylist.clone();
|
||||
</span><span class="boring"> let mut handles = vec![];
|
||||
</span><span class="boring"> let handle = thread::spawn(move || {
|
||||
</span><span class="boring"> // This simulates some I/O resource
|
||||
</span><span class="boring"> for event in rx {
|
||||
</span><span class="boring"> println!("REACTOR: {:?}", event);
|
||||
</span><span class="boring"> let rl_clone = rl_clone.clone();
|
||||
</span><span class="boring"> match event {
|
||||
</span><span class="boring"> Event::Close => break,
|
||||
</span><span class="boring"> Event::Timeout(waker, duration, id) => {
|
||||
</span><span class="boring"> let event_handle = thread::spawn(move || {
|
||||
</span><span class="boring"> thread::sleep(Duration::from_secs(duration));
|
||||
</span><span class="boring"> rl_clone.lock().map(|mut rl| rl.push(id)).unwrap();
|
||||
</span><span class="boring"> waker.wake();
|
||||
</span><span class="boring"> });
|
||||
</span><span class="boring">
|
||||
</span><span class="boring"> handles.push(event_handle);
|
||||
</span><span class="boring"> }
|
||||
</span><span class="boring"> }
|
||||
</span><span class="boring"> }
|
||||
</span><span class="boring">
|
||||
</span><span class="boring"> for handle in handles {
|
||||
</span><span class="boring"> handle.join().unwrap();
|
||||
</span><span class="boring"> }
|
||||
</span><span class="boring"> });
|
||||
</span><span class="boring">
|
||||
</span><span class="boring"> Reactor {
|
||||
</span><span class="boring"> readylist,
|
||||
</span><span class="boring"> dispatcher: tx,
|
||||
</span><span class="boring"> handle: Some(handle),
|
||||
</span><span class="boring"> }
|
||||
</span><span class="boring"> }
|
||||
</span><span class="boring">
|
||||
</span><span class="boring"> fn register(&mut self, duration: u64, waker: Waker, data: usize) {
|
||||
</span><span class="boring"> self.dispatcher
|
||||
</span><span class="boring"> .send(Event::Timeout(waker, duration, data))
|
||||
</span><span class="boring"> .unwrap();
|
||||
</span><span class="boring"> }
|
||||
</span><span class="boring">
|
||||
</span><span class="boring"> fn close(&mut self) {
|
||||
</span><span class="boring"> self.dispatcher.send(Event::Close).unwrap();
|
||||
</span><span class="boring"> }
|
||||
</span><span class="boring">
|
||||
</span><span class="boring"> fn is_ready(&self, id_to_check: usize) -> bool {
|
||||
</span><span class="boring"> self.readylist
|
||||
</span><span class="boring"> .lock()
|
||||
</span><span class="boring"> .map(|rl| rl.iter().any(|id| *id == id_to_check))
|
||||
</span><span class="boring"> .unwrap()
|
||||
</span><span class="boring"> }
|
||||
</span><span class="boring">}
|
||||
</span><span class="boring">
|
||||
</span><span class="boring">impl Drop for Reactor {
|
||||
</span><span class="boring"> fn drop(&mut self) {
|
||||
</span><span class="boring"> self.handle.take().map(|h| h.join().unwrap()).unwrap();
|
||||
</span><span class="boring"> }
|
||||
</span><span class="boring">}
|
||||
</span></code></pre></pre>
|
||||
<p>I added a debug printout of the events the reactor registered interest for so we can observe
|
||||
two things:</p>
|
||||
<ol>
|
||||
@@ -871,6 +874,18 @@ do really hope that you do continue to explore further.</p>
|
||||
|
||||
|
||||
|
||||
<script type="text/javascript">
|
||||
window.playpen_line_numbers = true;
|
||||
</script>
|
||||
|
||||
|
||||
|
||||
<script type="text/javascript">
|
||||
window.playpen_copyable = true;
|
||||
</script>
|
||||
|
||||
|
||||
|
||||
<script src="ace.js" type="text/javascript" charset="utf-8"></script>
|
||||
<script src="editor.js" type="text/javascript" charset="utf-8"></script>
|
||||
<script src="mode-rust.js" type="text/javascript" charset="utf-8"></script>
|
||||
|
||||
Reference in New Issue
Block a user