text
stringlengths
0
3.16k
source
stringclasses
1 value
Runtimes, Wakers, and the Reactor-Executor Pattern 180 Note that we need to pass in an Events collection to mio 's Poll::poll method, but since there is only one top-level future to run, we don't really care which event happened; we only care that something happened and that it most likely means that data is ready (rem...
9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf
Improving our base example 181 . unwrap(); } let mut buff = vec![0u8; 4096]; loop { match self. stream. as_mut(). unwrap(). read(&mut buff) { Ok(0) => { let s = String::from_utf8_lossy(&self. buffer); break Poll State::Ready(s. to_string()); } Ok(n) => { self. buffer. extend(&buff[0..n]); continue; } Err(e) if e. kind(...
9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf
Runtimes, Wakers, and the Reactor-Executor Pattern 182 Schedule other tasks HTTP/1. 1 200 OK content-length: 11 connection: close content-type: text/plain; charset=utf-8 date: Thu, 16 Nov xxxx xx:xx:xx GMT Hello World1 FIRST POLL-START OPERATION Schedule other tasks Schedule other tasks Schedule other tasks Schedule ot...
9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf
Improving our base example 183 Hello Async Await Note If you run the example on Windows, you'll see that you get two Schedule other tasks messages after each other. The reason for that is that Windows emits an extra event when the Tcp Stream is dropped on the server end. This doesn't happen on Linux. Filtering out thes...
9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf
Runtimes, Wakers, and the Reactor-Executor Pattern 184 To give you a few examples, you could use a separate reactor for handling timers (for example, when you want a task to sleep for a given time), or you might want to implement a thread pool for handling CPU-intensive or blocking tasks as a reactor that wakes up the ...
9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf
Creating a proper runtime 185 Figure 8. 6-A loosely coupled reactor and executor It's no coincidence that we land on the same design as what we have in Rust today. It's a minimal design from Rust's point of view, but it allows for a wide variety of runtime designs without laying too many restrictions for the future. No...
9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf
Runtimes, Wakers, and the Reactor-Executor Pattern 186 Figure 8. 7-Executor and reactor: final design We have two parts that have no direct dependency on each other. We have an Executor that schedules tasks and passes on a Waker when polling a future that eventually will be caught and stored by the Reactor. When the Re...
9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf
Step 1-Improving our runtime design by adding a Reactor and a Waker 187 Step 1-Improving our runtime design by adding a Reactor and a Waker In this step, we'll make the following changes: 1. Change the project structure so that it reflects our new design. 2. Find a way for the executor to sleep and wake up that does no...
9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf
Runtimes, Wakers, and the Reactor-Executor Pattern 188 |--http. rs |--main. rs |--runtime. rs To set everything up, we start by deleting everything in runtime. rs and replacing it with the following lines of code: ch08/b-reactor-executor/src/runtime. rs pub use executor::{spawn, Executor, Waker}; pub use reactor::react...
9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf
Step 1-Improving our runtime design by adding a Reactor and a Waker 189 Important note Our Waker relies on calling park/unpark on the Thread type from the standard library. This is OK for our example since it's easy to understand, but given that any part of the code (including any libraries you use) can get a handle to...
9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf
Runtimes, Wakers, and the Reactor-Executor Pattern 190 ready_queue -This is a reference that can be shared between threads to a Vec<usize>, where usize represents the ID of a task that's in the ready queue. We share this object with the executor so that we can push the task ID associated with the Waker onto that queue ...
9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf
Step 1-Improving our runtime design by adding a Reactor and a Waker 191 Changing the Future definition Since our Future definition is in the future. rs file, we start by opening that file. The first thing we need to change is to pull in the Waker so that we can use it. At the top of the file, add the following code: ch...
9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf
Runtimes, Wakers, and the Reactor-Executor Pattern 192 The compiler will complain about not finding the reactor yet, but we'll get to that shortly. Next, we have to navigate to the impl Future for Http Get Future block, where we need to change the poll method so that it accepts a &Waker argument: ch08/b-reactor-executo...
9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf
Step 2-Implementing a proper Executor 193 Hand out Waker types so that they can sleep when there is nothing to do and wake up when one of the top-level futures can progress Enable us to run several executors by having each run on its dedicated OS thread Note It's worth mentioning that our executor won't be fully multit...
9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf
Runtimes, Wakers, and the Reactor-Executor Pattern 194 The thread_local! macro lets us define a static variable that's unique to the thread it's first called from. This means that all threads we create will have their own instance, and it's impossible for one thread to access another thread's CURRENT_EXEC variable. We ...
9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf
Step 2-Implementing a proper Executor 195 The next function is an important one. The spawn function allows us to register new top-level futures with our executor from anywhere in our program: ch08/b-reactor-executor/src/runtime/executor. rs pub fn spawn<F>(future: F) where F: Future<Output = String> + 'static, { CURREN...
9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf
Runtimes, Wakers, and the Reactor-Executor Pattern 196 The Executor struct is very simple, and there is only one line of code to add: ch08/b-reactor-executor/src/runtime/executor. rs pub struct Executor; Since all the state we need for our example is held in Executor Core, which is a static thread-local variable, our E...
9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf
Step 2-Implementing a proper Executor 197 fn insert_task(&self, id: usize, task: Task) { CURRENT_EXEC. with(|q| q. tasks. borrow_mut(). insert(id, task)); } fn task_count(&self)-> usize { CURRENT_EXEC. with(|q| q. tasks. borrow(). len()) } So, we have six methods here: new -Creates a new Executor instance. For simplici...
9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf
Runtimes, Wakers, and the Reactor-Executor Pattern 198 let mut future = match self. get_future(id) { Some(f) => f, // guard against false wakeups None => continue, }; let waker = self. get_waker(id); match future. poll(&waker) { Poll State::Not Ready => self. insert_task(id, future), Poll State::Ready(_) => continue, }...
9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf
Step 3-Implementing a proper Reactor 199 3. Every time we loop, we create an inner while let Some(... ) loop that runs as long as there are tasks in ready_queue. 4. If there is a task in ready_queue, we take ownership of the Future object by removing it from the collection. We guard against false wakeups by just contin...
9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf
Runtimes, Wakers, and the Reactor-Executor Pattern 200 Provide the necessary mechanisms for leaf futures such as Http Get Future, to register and deregister interests in events Provide a way for leaf futures to store the last received Waker When we're done with this step, we should have everything we need for our runti...
9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf
Step 3-Implementing a proper Reactor 201 ch08/b-reactor-executor/src/runtime/reactor. rs pub fn reactor()-> &'static Reactor { REACTOR. get(). expect("Called outside an runtime context") } The next thing we do is define our Reactor struct: ch08/b-reactor-executor/src/runtime/reactor. rs pub struct Reactor { wakers: Wak...
9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf
Runtimes, Wakers, and the Reactor-Executor Pattern 202 self. registry. deregister(stream). unwrap(); } pub fn next_id(&self)-> usize { self. next_id. fetch_add(1, Ordering::Relaxed) } } Let's briefly explain what these four methods do: register -This method is a thin wrapper around Registry::register, which we know fro...
9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf
Step 3-Implementing a proper Reactor 203 let Token(id) = e. token(); let wakers = wakers. lock(). unwrap(); if let Some(waker) = wakers. get(&id) { waker. wake(); } } } } This function takes a Poll instance and a Wakers collection as arguments. Let's go through it step by step: The first thing we do is create an events...
9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf
Runtimes, Wakers, and the Reactor-Executor Pattern 204 let poll = Poll::new(). unwrap(); let registry = poll. registry(). try_clone(). unwrap(); let next_id = Atomic Usize::new(1); let reactor = Reactor { wakers: wakers. clone(), registry, next_id, }; REACTOR. set(reactor). ok(). expect("Reactor already running"); spaw...
9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf
Step 3-Implementing a proper Reactor 205 buffer: Vec<u8>, path: String, id: usize, } We also need to retrieve a new ID from the reactor when the future is created: ch08/b-reactor-executor/src/http. rs impl Http Get Future { fn new(path: String)-> Self { let id = reactor(). next_id(); Self { stream: None, buffer: vec![]...
9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf
Runtimes, Wakers, and the Reactor-Executor Pattern 206 let s = String::from_utf8_lossy(&self. buffer); runtime::reactor(). deregister(self. stream. as_mut(). unwrap(), self. id); break Poll State::Ready(s. to_string()); } Ok(n) => { self. buffer. extend(&buff[0..n]); continue; } Err(e) if e. kind() == Error Kind::Would...
9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf
Step 3-Implementing a proper Reactor 207 use future::{Future, Poll State}; use runtime::Waker; Next, we need to make sure that we initialize our runtime and pass in our future to executor. block_on. Our main function should look like this: ch08/b-reactor-executor/src/main. rs fn main() { let mut executor = runtime::ini...
9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf
Runtimes, Wakers, and the Reactor-Executor Pattern 208 Experimenting with our new runtime If you remember from Chapter 7, we implemented a join_all method to get our futures running concurrently. In libraries such as Tokio, you'll find a join_all function too, and the slightly more versatile Futures Unordered API that ...
9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf
Experimenting with our new runtime 209 To run this example, follow these steps: 1. Replace everything below the imports in main. rs with the preceding code. 2. Run corofy. /src/main. rs. 3. Copy everything from main_corofied. rs to main. rs and delete main_corofied. rs. 4. Fix the fact that corofy doesn't know we chang...
9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf
Runtimes, Wakers, and the Reactor-Executor Pattern 210 } executor. block_on(async_main()); handles. into_iter(). for_each(|h| h. join(). unwrap()); } coroutine fn request(i: usize) { let path = format!("/{}/Hello World{i}", i * 1000); let txt = Http::get(&path). wait; let txt = txt. lines(). last(). unwrap_or_default()...
9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf
Summary 211 Now, if you run the program, you'll see that it still only takes around 4 seconds to run, but this time we made 60 GET requests instead of 5. This time, we ran our futures both concurrently and in parallel. At this point, you can continue experimenting with shorter delays or more requests and see how many c...
9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf
Runtimes, Wakers, and the Reactor-Executor Pattern 212 So, the next chapter will explain pinning in Rust in a practical way so that you understand why we need it, what it does, and how to do it. However, you absolutely deserve a break after this chapter, so take some fresh air, sleep, clear your mind, and grab some cof...
9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf
9 Coroutines, Self-Referential Structs, and Pinning In this chapter, we'll start by improving our coroutines by adding the ability to store variables across state changes. We'll see how this leads to our coroutines needing to take references to themselves and the issues that arise as a result of that. The reason for de...
9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf
Coroutines, Self-Referential Structs, and Pinning 214 Pinning in Rust Improving our example 4-pinning to the rescue Technical requirements The examples in this chapter will build on the code from the previous chapter, so the requirements are the same. The examples will all be cross-platform and work on all platforms th...
9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf
Improving our example 1-variables 215 Let's start by setting up our example. We'll use the “library” code from d-multiple-threads example in Chapter 8 (our last version of the example), but we'll change the main. rs file by adding a shorter and simpler example. Let's set up the base example that we'll iterate on and im...
9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf
Coroutines, Self-Referential Structs, and Pinning 216 use runtime::Waker; fn main() { let mut executor = runtime::init(); executor. block_on(async_main()); } coroutine fn async_main() { println!("Program starting"); let txt = Http::get("/600/Hello Async Await"). wait; println!("{txt}"); let txt = Http::get("/400/Hello ...
9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf
Improving our example 1-variables 217 Note Remember that we need delayserver running in a terminal window so that we get a response to our HTTP GET requests. See the Technical requirements section for more information. Now that we've got the boilerplate out of the way, it's time to start making the improvements we talk...
9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf
Coroutines, Self-Referential Structs, and Pinning 218 In this version, we simply create a counter variable at the top of our async_main function and increase the counter for each response we receive from the server. At the end, we print out how many responses we received. Note For brevity, I won't present the entire co...
9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf
Improving our example 1-variables 219 Note Futures created by async/await in Rust store this data in a slightly more efficient manner. In our example, we store every variable in a separate struct since I think it's easier to reason about, but it also means that the more variables we need to store, the more space our co...
9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf
Coroutines, Self-Referential Structs, and Pinning 220 //--------------------------------- let fut1 = Box::new( http::Http::get("/600/ Hello Async Await")); self. state = State0::Wait1(fut1); // save stack } Okay, so there are some important changes here that I've highlighted. Let's go through them: The first thing we d...
9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf
Improving our example 1-variables 221 Hmm, this is interesting. I've highlighted the changes we need to make. The first thing we do is to restore the stack by taking ownership over the counter ( take() replaces the value currently stored in self. stack. counter with None in this case) and writing it to a variable with ...
9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf
Coroutines, Self-Referential Structs, and Pinning 222 } Poll State::Not Ready => break Poll State::Not Ready, } } Since there are no more wait points in our program, the rest of the code goes into this segment and since we're done with counter at this point, we can simply drop it by letting it go out of scope. If our v...
9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf
Improving our example 2-references 223 let writer = &mut buffer; println!("Program starting"); let txt = http::Http::get("/600/Hello Async Await"). wait; writeln!(writer, "{txt}"). unwrap(); let txt = http::Http::get("/400/Hello Async Await"). wait; writeln!(writer, "{txt}"). unwrap(); println!( "{}", buffer); } So, in...
9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf
Coroutines, Self-Referential Structs, and Pinning 224 The only other thing we need to change is the Future::poll implementation: ch09/b-coroutines-references/src/main. rs State0::Start => { // initialize stack (hoist variables) self. stack. buffer = Some(String::from("\n BUFFER:\ n----\n")); self. stack. writer = Some(...
9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf
Improving our example 2-references 225 Let's take a look at what happens after the first wait point: ch09/b-coroutines-references/src/main. rs State0::Wait1(ref mut f1) => { match f1. poll(waker) { Poll State::Ready(txt) => { // Restore stack let writer = unsafe { &mut *self. stack. writer. take(). unwrap() }; //----Co...
9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf
Coroutines, Self-Referential Structs, and Pinning 226 The last part is when we've reached Wait2 and our future returns Poll State::Ready : State0::Wait2(ref mut f2) => { match f2. poll(waker) { Poll State::Ready(txt) => { // Restore stack let buffer = self. stack. buffer. as_ref(). take(). unwrap(); let writer = unsafe...
9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf
Improving our example 3-this is... not... good... 227 Let's take a look at what happens when we run our program by writing cargo run : Program starting FIRST POLL-START OPERATION main: 1 pending tasks. Sleep until notified. FIRST POLL-START OPERATION main: 1 pending tasks. Sleep until notified. BUFFER:----HTTP/1. 1 200...
9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf
Coroutines, Self-Referential Structs, and Pinning 228 Tip This example is located in this book's Git Hub repository in the ch09/c-coroutines-problem folder. With that, everything has been set up. Back to the optimization. Y ou see, new insights into the workload our runtime will handle in real life indicate that most f...
9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf
Discovering self-referential structs 229 Let's try to run our program and see what we get: Program starting FIRST POLL-START OPERATION main: 1 pending tasks. Sleep until notified. FIRST POLL-START OPERATION main: 1 pending tasks. Sleep until notified. /400/Hello Asyn free(): double free detected in tcache 2 Aborted Wai...
9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf
Coroutines, Self-Referential Structs, and Pinning 230 6. The next time we poll the future, we restore the stack by dereferencing the pointer we hold for our writer variable. However, there's a big problem: the pointer is now pointing to the old location on the stack where the future was located at the first poll. 7. Th...
9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf
Discovering self-referential structs 231 Note It can be very hard to detect these issues, and creating simple examples where a move like this causes serious issues is surprisingly difficult. The reason for this is that even though we move everything, the old values are not zeroed or overwritten immediately. Often, they...
9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf
Coroutines, Self-Referential Structs, and Pinning 232 Figure 9. 2-Move, clone, and copy A move will in many ways be like a deep copy of everything in our struct that's located on the stack. This is problematic when you have a pointer that points to self, like we have with self-referential structs, since self will start...
9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf
Pinning in Rust 233 Pinning in Rust The following diagram shows a slightly more complex self-referential struct so that we have something visual to help us understand: Figure 9. 3-Moving a self-referential struct with three fields At a very high level, pinning makes it possible to rely on data that has a stable memory ...
9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf
Coroutines, Self-Referential Structs, and Pinning 234 Pinning in theory Pinning is a part of Rust's standard library and consists of two parts: the type, Pin, and the marker-trait, Unpin. Pinning is only a language construct. There is no special kind of location or memory that you move values to so they get pinned. The...
9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf
Pinning in Rust 235 Structural pinning is connected to pin projections in the sense that, if you have Pin<&mut T> where T has one field, a, that can be moved freely and one that can't be moved, b, you can do the following: ‚Write a pin projection for a with the fn a(self: Pin<&mut self>)-> &A signature. In this case, w...
9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf
Coroutines, Self-Referential Structs, and Pinning 236 This is very much like futures that are not self-referential until they're polled, as we saw in our previous example. Let's write the impl block for Maybe Self Ref and take a look at the code:: ch09/d-pin/src/main. rs impl Maybe Self Ref { fn init(self: Pin<&mut Sel...
9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf
Pinning in Rust 237 Here, we pin Maybe Self Ref to the heap and initialize it. We print out the value of a and then mutate the data through the self-reference in b, and set its value to 2. If we look at the output, we'll see that everything looks as expected: Finished dev [unoptimized + debuginfo] target(s) in 0. 56s R...
9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf
Coroutines, Self-Referential Structs, and Pinning 238 println!("{}", x. as_ref(). a); } The noticeable difference here is that it's unsafe to pin to the stack, so now, we need unsafe both as users of Maybe Self Ref and as implementors. If we run the example with cargo run, the output will be the same as in our first ex...
9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf
Pinning in Rust 239 In this example, we create two instances of Maybe Self Ref called x and y. Then, we create a scope where we pin x and set the value of x. a to 2 by dereferencing the self-reference in b, as we did previously. Now, when we exit the scope, x isn't pinned anymore, which means we can take a mutable refe...
9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf
Coroutines, Self-Referential Structs, and Pinning 240 Tip In this book's Git Hub repository, you'll find a function called stack_pinning_macro() in the ch09/d-pin/src/main. rs file. This function shows the preceding example but using Rust's pin! macro. Pin projections and structural pinning Before we leave the topic of...
9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf
Improving our example 4-pinning to the rescue 241 impl Foo { fn a(self: Pin<&mut Self>)-> Pin<&mut Maybe Self Ref> { unsafe { self. map_unchecked_mut(|s| &mut s. a) } } fn b(self: Pin<&mut Self>)-> &mut String { unsafe { &mut self. get_unchecked_mut(). b } } } Note that these methods will only be callable when Foo is p...
9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf
Coroutines, Self-Referential Structs, and Pinning 242 Tip Y ou'll find the example code we'll go through here in this book's Git Hub repository under the ch09/e-coroutines-pin folder. Now that we have a new folder set up, let's start making the necessary changes. The logical place to start is our Future definition in f...
9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf
Improving our example 4-pinning to the rescue 243 Since self is now Pin<&mut Self>, there are several small changes we need to make so that the borrow checker stays happy. Let's start from the top: ch09/e-coroutines-pin/src/http. rs let id = self. id; if self. stream. is_none() { println!("FIRST POLL-START OPERATION");...
9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf
Coroutines, Self-Referential Structs, and Pinning 244 Main. rs Let's start from the top and make sure we have the correct imports: ch09/e-coroutines-pin/src/main. rs mod future; mod http; mod runtime; use future::{Future, Poll State}; use runtime::Waker; use std::{fmt::Write, marker::Phantom Pinned, pin::Pin }; This ti...
9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf
Improving our example 4-pinning to the rescue 245 } The last thing we need to change is the poll method. Let's start with the function signature: ch09/e-coroutines-pin/src/main. rs fn poll(self: Pin<&mut Self>, waker: &Waker)-> Poll State<Self::Output> The easiest way I found to change our code was to simply define a n...
9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf
Coroutines, Self-Referential Structs, and Pinning 246 The next thing we need to change is to have the futures we store in our wait states pinned. We can do this by calling Box::pin instead of Box::new : ch09/e-coroutines-pin/src/main. rs let fut1 = Box:: pin(http::Http::get("/600/Hello Async Await")); let fut2 = Box:: ...
9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf
Improving our example 4-pinning to the rescue 247 It won't even let us poll the future anymore without us pinning it first since poll is only callable for Pin<&mut Self> types and not &mut self anymore. So, we have to decide whether we pin the value to the stack or the heap before we even try to poll it. In our case, o...
9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf
Coroutines, Self-Referential Structs, and Pinning 248 Summary What a ride, huh? If you've got to the end of this chapter, you've done a fantastic job, and I have good news for you: you pretty much know everything about how Rust's futures work and what makes them special already. All the complicated topics are covered. ...
9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf
Summary 249 The ability to spawn new tasks onto the runtime so that one task can spawn hundreds of new tasks that will run concurrently A reactor that uses epoll /kqueue /IOCP under the hood to efficiently wait for and respond to new events reported by the operating system I think this is pretty cool. We're not quite d...
9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf
9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf
10 Creating Y our Own Runtime In the last few chapters, we covered a lot of aspects that are relevant to asynchronous programming in Rust, but we did that by implementing alternative and simpler abstractions than what we have in Rust today. This last chapter will focus on bridging that gap by changing our runtime so th...
9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf
Creating Your Own Runtime 252 The only thing you need is Rust installed and the book's repository downloaded locally. All the code in this chapter can be found in the ch10 folder. We'll use delayserver in this example as well, so you need to open a separate terminal, enter the delayserver folder at the root of the repo...
9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf
Technical requirements 253 Other than the differences outlined above, everything else can stay pretty much as is. For the most part, we're renaming and refactoring this time. Now that we've got an idea of what we need to do, it's time to set everything up so we can get our new example up and running. Note Even though w...
9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf
Creating Your Own Runtime 254 fn main() { let mut executor = runtime::init(); executor. block_on(async_main()); } async fn async_main() { println!("Program starting"); let txt = Http::get("/600/Hello Async Await"). await; println!("{txt}"); let txt = Http::get("/400/Hello Async Await"). await; println!("{txt}"); } No n...
9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf
Technical requirements 255 pin::Pin, task::{Context, Poll}, }; We have to do some minor refactoring in the poll implementation for Http Get Future. First, we need to change the signature of the poll function so it complies with the new Future trait: ch10/a-rust-futures/src/http. rs fn poll(mut self: Pin<&mut Self>, cx:...
9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf
Creating Your Own Runtime 256 continue; } Err(e) if e. kind() == Error Kind::Would Block => { // always store the last given Waker runtime::reactor(). set_waker(cx, self. id); break Poll::Pending ; } Err(e) => panic!("{e:?}"), } } That's it for this file. Not bad, huh? Let's take a look at what we need to change in our...
9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf
Technical requirements 257 Creating a waker in Rust can be quite a complex task since Rust wants to give us maximum flexibility on how we choose to implement wakers. The reason for this is twofold: Wakers must work just as well on a server as it does on a microcontroller A waker must be a zero-cost abstraction Realizin...
9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf
Creating Your Own Runtime 258 We can keep the implementation of wake pretty much the same, but we put it in the implementation of the Wake trait instead of just having a wake function on My Waker : ch10/a-rust-futures/src/runtime/executor. rs impl Wake for My Waker { fn wake(self: Arc<Self>) { self. ready_queue . lock(...
9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf
Technical requirements 259 The next step is to change how we create a waker and wrap it in a Context struct in the block_ on function: ch10/a-rust-futures/src/runtime/executor. rs... // guard against false wakeups None => continue, }; let waker: Waker = self. get_waker(id). into(); let mut cx = Context::from_waker(&wak...
9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf
Creating Your Own Runtime 260 ch10/a-rust-futures/src/runtime/reactor. rs use mio::{net::Tcp Stream, Events, Interest, Poll, Registry, Token}; use std::{ collections::Hash Map, sync::{ atomic::{Atomic Usize, Ordering}, Arc, Mutex, Once Lock, }, thread, task::{Context, Waker}, }; There are two minor changes we need to m...
9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf
Experimenting with our runtime 261 We should get the same output as we've seen before: Program starting FIRST POLL-START OPERATION main: 1 pending tasks. Sleep until notified. HTTP/1. 1 200 OK content-length: 15 [==== ABBREVIATED ====] Hello Async Await main: All tasks are finished That's pretty neat, isn't it? So, now...
9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf
Creating Your Own Runtime 262 The first thing we do is add reqwest as a dependency in Cargo. toml by typing the following: cargo add reqwest@0. 11 Next, let's change our async_main function so we use reqwest instead of our own HTTP client: ch10/b-rust-futures-examples/src/main. rs (async_main2) async fn async_main() { ...
9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf
Experimenting with our runtime 263 Adding this to the top of our async_main function should work: ch10/b-rust-futures-examples/src/main. rs (async_main2) use tokio::runtime::Runtime; async fn async_main let rt = Runtime::new(). unwrap(); let _guard = rt. enter(); println!("Program starting"); let url = "http://127. 0. ...
9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf
Creating Your Own Runtime 264 Okay, so now everything works as expected. The only difference is that we get woken up a few extra times, but the program finishes and produces the expected result. Before we discuss what we just witnessed, let's do one more experiment. Isahc is an HTTP client library that promises to be e...
9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf
Challenges with asynchronous Rust 265 Why does all this have to be so unintuitive? The answer to that brings us to the topic of common challenges that we all face when programming with async Rust, so let's cover some of the most noticeable ones and explain the reason they exist so we can figure out how to best deal wit...
9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf
Creating Your Own Runtime 266 In practice, that means that Isahc brings its own reactor since it comes with the machinery to store wakers and call wake on them when an operation is ready. The reactor is started implicitly. Incidentally, this is also one of the major differences between async_std and Tokio. Tokio requir...
9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf
Challenges with asynchronous Rust 267 Tasks We've used the terms tasks and futures without making the difference explicitly clear, so let's clear that up here. We first covered tasks in Chapter 1, and they still retain the same general meaning, but when talking about runtimes in Rust, they have a more specific definiti...
9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf
Creating Your Own Runtime 268 Let's take spawning as an example. When you write a high-level async library in Rust, such as a web server, you'll likely want to be able to spawn new tasks (top-level futures). For example, each connection to the server will most likely be a new task that you want to spawn onto the execut...
9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf
The future of asynchronous Rust 269 Before we round off this chapter, let's spend a little time talking about what we should expect in the future when it comes to asynchronous programming in Rust. The future of asynchronous Rust Some of the things that make async Rust different from other languages are unavoidable. Asy...
9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf
Creating Your Own Runtime 270 Depending on how you've followed along and how much you've experimented with the examples we created along the way, it's up to you what project to take on yourself if you want to learn more. There is an important aspect of learning that only happens when you experiment on your own. Pick ev...
9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf
Summary 271 What runtime you start with depends a bit on what crates you're using the most. Smol and async-std share a lot of implementation details and will behave similarly. Their big selling point is that their API strives to stay as close as possible to the standard library. Combined with the fact that the reactors...
9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf
Creating Your Own Runtime 272 Epilogue So, you have reached the end. First of all, congratulations! Y ou've come to the end of quite a journey! We started by talking about concurrency and parallelism in Chapter 1. We even covered a bit about the history, CPUs and OSs, hardware, and interrupts. In Chapter 2, we discusse...
9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf
Epilogue 273 Now that we're at the end I want to thank you for reading all the way to the end. I wanted this book to feel like a journey we took together, not like a lecture. I wanted you to be the focus, not me. I hope I succeeded with that, and I genuinely hope that you learned something that you find useful and can ...
9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf
9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf
Index Symbols 1:1 threading 29 A address space 30 application binary interface (ABI) 97 arithmetic logic units (ALUs) 5 Assembly language 102 asymmetric coroutines 39, 40 async/await keywords 154, 155 asynchronous programming versus concurrency 13 asynchronous Rust challenges 265 future 269 async runtime mental model 1...
9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf
Index276 complex instruction set computers (CISC) 97 concurrency 9 relation, to I/O 11 right reference frame, selecting 12 use cases 11 versus asynchronous programming 12 versus parallelism 7, 8, 9, 10 concurrent 8 continuation-passing style 39 cooperative multitasking 5, 26 corofy 155, 156 coroutine implementation 227...
9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf
Index277 future. rs 254 futures 38, 39 G generators versus, coroutines 139 Go 112 green threads 33 guard function 121-125 H hand-written coroutines code, writing 153, 154 example 139, 140 futures module 141 HTTP module 142-146 lazy future 146, 147 hardware interrupts 6, 20, 22 highest level of abstraction 61 http. rs 2...
9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf
Index278 M M:1 threading 33 mac OS OS-provided API, using in 56-58 raw syscall on 54, 55 main. rs file 84-93, 253, 254 memory management unit (MMU) 17 mental model, of async runtime 131-133 M*N threading 28, 33 move 231, 232 multicore processors 6 multiprotocol file transfer 265 multitasking 4 hyper-threading 5 multico...
9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf
Index279 pointers 231 polling 46 Poll module 81-84 preemptive multitasking 5 pre-empt running tasks 26 privilege level 18 process 30 promises 38, 39 proper Executor implementing 192-199 proper Reactor implementing 199-207 proper runtime creating 184-186 R raw syscall on Linux 52-54 on mac OS 54, 55 reactor 170 reactor....
9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf