text stringlengths 0 3.16k | source stringclasses 1
value |
|---|---|
Create Your Own Event Queue 80 Figure 4. 1-Edge-triggered versus level-triggered events mio doesn't, at the time of writing, support EPOLLONESHOT and uses epoll in an edge-triggered mode, which we will do as well in our example. What about waiting on epoll_wait in multiple threads? As long as we only have one Poll inst... | 9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf |
The Poll module 81 Now that we've covered the hard part of this chapter and gotten a high-level overview of how epoll works, it's time to implement our mio-inspired API in poll. rs. The Poll module If you haven't written or copied the code we presented in the Design and introduction to epoll section, it's time to do it... | 9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf |
Create Your Own Event Queue 82 The last method on Poll is the most interesting one. It's the poll function, which will park the current thread and tell the operating system to wake it up when an event has happened on a source we're tracking, or the timeout has elapsed, whichever comes first. We also close the impl Poll... | 9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf |
The Poll module 83 Next up is our Registry struct. We will only implement one method, called register, and lastly, we'll implement the Drop trait for it, closing the epoll instance: ch04/a-epoll/src/poll. rs impl Registry { pub fn register(&self, source: &Tcp Stream, token: usize, interests: i32)-> Result<()> { let mut... | 9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf |
Create Your Own Event Queue 84 The operation we want to perform on the epoll queue is adding interest in events on a new file descriptor. Therefore, we set the op argument to the ffi::EPOLL_CTL_ADD constant value. Next up is the call to ffi::epoll_ctl. We pass in the file descriptor to the epoll instance first, then we... | 9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf |
The main program 85 The first thing we do is to make sure our main. rs file is set up correctly: ch04/a-epoll/src/main. rs use std::{io::{self, Read, Result, Write}, net::Tcp Stream}; use ffi::Event; use poll::Poll; mod ffi; mod poll; We import a few types from our own crate and from the standard library, which we'll n... | 9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf |
Create Your Own Event Queue 86 The first part of the main function looks like this: fn main()-> Result<()> { let mut poll = Poll::new()?; let n_events = 5; let mut streams = vec![]; let addr = "localhost:8080"; for i in 0..n_events { let delay = (n_events-i) * 1000; let url_path = format!("/{delay}/request-{i}"); let r... | 9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf |
The main program 87 Note For simplicity, we use the index the event will have in the streams collection as its ID. This ID will be the same as the i variable in our loop. For example, in the first loop, i will be 0; it will also be the first stream to be pushed to our streams collection, so the index will be 0 as well.... | 9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf |
Create Your Own Event Queue 88 To continue with the code, the next step is setting Tcp Stream to non-blocking by calling Tcp Stream::set_nonblocking(true). After that, we write our request to the server before we register interest in read events by setting the EPOLLIN flag bit in the interests bitmask. For each iterati... | 9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf |
The main program 89 If there are events to be handled, we pass these on to the handle_events function together with a mutable reference to our streams collection. The last part of main is simply to write FINISHED to the console to let us know we exited main at that point. The last bit of code in this chapter is the han... | 9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf |
Create Your Own Event Queue 90 In the loop, we retrieve the token that identifies which Tcp Stream we received an event for. As we explained earlier in this example, this token is the same as the index for that particular stream in the streams collection, so we can simply use it to index into our streams collection and... | 9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf |
The main program 91 Now, if we run our program, we should get the following output: RECEIVED: Event { events: 1, epoll_data: 4 } HTTP/1. 1 200 OK content-length: 9 connection: close content-type: text/plain; charset=utf-8 date: Wed, 04 Oct 2023 15:29:09 GMT request-4------RECEIVED: Event { events: 1, epoll_data: 3 } HT... | 9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf |
Create Your Own Event Queue 92 content-length: 9 connection: close content-type: text/plain; charset=utf-8 date: Wed, 04 Oct 2023 15:29:13 GMT request-0------FINISHED As you see, the responses are sent in reverse order. Y ou can easily confirm this by looking at the output on the terminal on running the delayserver ins... | 9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf |
Summary 93 Before we leave this example, I wanted to point out how few changes we need to make to have our example use mio as the event loop instead of the one we created. In the repository under ch04/b-epoll-mio, you'll see an example where we do the exact same thing using mio instead. It only requires importing a few... | 9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf |
Create Your Own Event Queue 94 At least you now have a good foundation for further exploration. Y ou can expand on our simple example and create a proper event loop that handles connecting, writing, timeouts, and scheduling; you can dive deeper into kqueue and IOCP by looking at how mio solves that problem; or you can ... | 9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf |
5 Creating Our Own Fibers In this chapter, we take a deep dive into a very popular way of handling concurrency. There is no better way of getting a fundamental understanding of the subject than doing it yourself. Fortunately, even though the topic is a little complex, we only need around 200 lines of code to get a full... | 9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf |
Creating Our Own Fibers 96 Note In this chapter, we'll use the terms “fibers” and “green threads” to refer to this exact implementation of stackful coroutines. The term “threads” in this chapter, which is used in the code we write, will refer to the green threads/fibers we implement in our example and not OS threads. T... | 9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf |
Background information 97 ch05/b-show-stack ch05/c-fibers In addition, you will get two more examples that I refer to in the book but that should be explored in the repository: ch05/d-fibers-closure : This is an extended version of the first example that might inspire you to do more complex things yourself. The example... | 9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf |
Creating Our Own Fibers 98 but require some operations to be handled by software that could be directly handled by the hardware in a CISC architecture. The x86-64 instruction set we'll focus on is an example of a CISC architecture. To add a little complexity (you know, it's not fun if it's too easy), there are differen... | 9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf |
Background information 99 The x86-64 ISA defines 16 general-purpose registers. These are registers the CPU provides for programmers to use for whatever they see fit. Note that programmers here include the ones that write the operating system, and they can lay additional restrictions on what registers you can use for wh... | 9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf |
Creating Our Own Fibers 100 Figure 5. 1-x86-64 CPU registers There are architectures that build upon this base and extend it, such as the Intel Advanced Vector Extensions (AVX ), which provide an additional 16 registers of 256 bits in width. Let's take a look at a page from the System V ABI specification: | 9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf |
Background information 101 Figure 5. 2-Register usage Figure 5. 1 shows an overview of the general-purpose registers in the x86-64 architecture. Out of special interest for us right now are the registers marked as callee saved. These are the registers we need to keep track of our context across function calls. It inclu... | 9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf |
Creating Our Own Fibers 102 If we want to issue a very specific set of commands to the CPU directly, we need to write small pieces of code in assembly. Fortunately, we only need to know some very basic assembly instructions for our first mission. Specifically, we need to know how to move values to and from registers: m... | 9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf |
An example we can build upon 103 One more thing to note is that the stack alignment on x86-64 is 16 bytes. Just remember this for later. An example we can build upon This is a short example where we will create our own stack and make our CPU return out of its current execution context and over to the stack we just crea... | 9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf |
Creating Our Own Fibers 104 In later examples, we will use all the registers marked as callee saved in the specification document I linked to. These are the registers described in the System V x86-64 ABI that we'll need to save our context, but right now, we only need one register to make the CPU jump over to our stack... | 9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf |
An example we can build upon 105 The first thing we do is set up the new stack and write the address to the function we want to run at a 16-byte offset from the top of the stack (the ABI dictates a 16-byte stack alignment, so the top of our stack frame must start at a 16-byte offset). We'll see how to create a continuo... | 9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf |
Creating Our Own Fibers 106 The next line is the asm! macro in the Rust standard library. It will check our syntax and provide an error message if it encounters something that doesn't look like valid Intel (by default) assembly syntax. asm!( The first thing the macro takes as input is the assembly template: "mov rsp, [... | 9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf |
An example we can build upon 107 Let's try to sum up what we do here with words: Move what's at the + 0x00 offset from the memory location that {compiler_chosen_general_ purpose_register} points to to the rsp register. The next line is the ret keyword, which instructs the CPU to pop a memory location off the stack and ... | 9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf |
Creating Our Own Fibers 108 } } So, in this function, we're actually creating our new stack. hello is a pointer already (a function pointer), so we can cast it directly as an u64 since all pointers on 64-bit systems will be, well, 64-bit. Then, we write this pointer to our new stack. Note We'll talk more about the stac... | 9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf |
The stack 109 In the next sections, we will talk about the stack in a bit more detail before we implement our fibers. It will be easier now that we have covered so much of the basics. The stack A stack is nothing more than a piece of contiguous memory. This is important to know. A computer only has memory, it doesn't h... | 9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf |
Creating Our Own Fibers 110 When we pass a pointer, we need to make sure we pass in a pointer to either address 0016, 0008, or 0000 in the example. The stack grows downwards, so we start at the top and work our way down. When we set the stack pointer in a 16-byte aligned stack, we need to make sure to put our stack poi... | 9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf |
The stack 111 mem: 2643866716675, val: 0 mem: 2643866716674, val: 0 mem: 2643866716673, val: 0 I LOVE WAKING UP ON A NEW STACK! I've printed out the memory addresses as u64 here, so it's easier to parse if you're not very familiar with hex. The first thing to note is that this is just a contiguous piece of memory, star... | 9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf |
Creating Our Own Fibers 112 When you start a process in most modern operating systems, the standard stack size is normally 8 MB, but it can be configured differently. This is enough for most programs, but it's up to the programmer to make sure we don't use more than we have. This is the cause of the dreaded stack overf... | 9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf |
Implementing our own fibers 113 We start off the example by enabling a specific feature we need, importing the asm macro, and defining a few constants: ch05/c-fibers/main. rs #![feature(naked_functions)] use std::arch::asm; const DEFAULT_STACK_SIZE: usize = 1024 * 1024 * 2; const MAX_THREADS: usize = 4; static mut RUNT... | 9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf |
Creating Our Own Fibers 114 #[derive(Partial Eq, Eq, Debug)] enum State { Available, Running, Ready, } struct Thread { stack: Vec<u8>, ctx: Thread Context, state: State, } #[derive(Debug, Default)] #[repr(C)] struct Thread Context { rsp: u64, r15: u64, r14: u64, r13: u64, r12: u64, rbx: u64, rbp: u64, } Runtime is goin... | 9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf |
Implementing our own fibers 115 Note The registers we save in our Thread Context struct are the registers that are marked as callee saved in Figure 5. 1. We need to save these since the ABI states that the callee (which will be our switch function from the perspective of the OS) needs to restore them before the caller ... | 9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf |
Creating Our Own Fibers 116 The first thing we do is to implement a new function on our Runtime struct: impl Runtime { pub fn new()-> Self { let base_thread = Thread { stack: vec![0_u8; DEFAULT_STACK_SIZE], ctx: Thread Context::default(), state: State::Running, }; let mut threads = vec![base_thread]; let mut available_... | 9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf |
Implementing our own fibers 117 This is where we start running our runtime. It will continually call t_yield() until it returns false, which means that there is no more work to do and we can exit the process: pub fn run(&mut self)-> ! { while self. t_yield() {} std::process::exit(0); } Note yield is a reserved word in ... | 9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf |
Creating Our Own Fibers 118 Let's present the function before we go on to explain the last part of it: #[inline(never)] fn t_yield(&mut self)-> bool { let mut pos = self. current; while self. threads[pos]. state != State::Ready { pos += 1; if pos == self. threads. len() { pos = 0; } if pos == self. current { return fal... | 9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf |
Implementing our own fibers 119 almost never a problem on debug builds, but in this case, our program will fail if the compiler inlines this function in a release build. The issue manifests itself by the runtime exiting before all the tasks are finished. Since we store Runtime as a static usize that we then cast as a *... | 9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf |
Creating Our Own Fibers 120 let size = available. stack. len(); unsafe { let s_ptr = available. stack. as_mut_ptr(). offset(size as isize); let s_ptr = (s_ptr as usize & !15) as *mut u8; std::ptr::write(s_ptr. offset(-16) as *mut u64, guard as u64); std::ptr::write(s_ptr. offset(-24) as *mut u64, skip as u64); std::ptr... | 9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf |
Implementing our own fibers 121 When we spawn a new fiber (or userland thread), we first check if there are any available userland threads (threads in Available state). If we run out of threads, we panic in this scenario, but there are several (better) ways to handle that. We'll keep things simple for now. When we find... | 9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf |
Creating Our Own Fibers 122 The guard function is called when the function that we passed in, f, has returned. When f returns, it means our task is finished, so we de-reference our Runtime and call t_return(). We could have made a function that does some additional work when a thread is finished, but right now, our t_r... | 9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf |
Implementing our own fibers 123 "mov rsp, [rsi + 0x00]", "mov r15, [rsi + 0x08]", "mov r14, [rsi + 0x10]", "mov r13, [rsi + 0x18]", "mov r12, [rsi + 0x20]", "mov rbx, [rsi + 0x28]", "mov rbp, [rsi + 0x30]", "ret", options(noreturn) ); } So, this is our full stack switch function. Y ou probably remember from our first e... | 9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf |
Creating Our Own Fibers 124 fn main() { let mut runtime = Runtime::new(); runtime. init(); runtime. spawn(|| { println!("THREAD 1 STARTING"); let id = 1; for i in 0..10 { println!("thread: {} counter: {}", id, i); yield_thread(); } println!("THREAD 1 FINISHED"); }); runtime. spawn(|| { println!("THREAD 2 STARTING"); le... | 9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf |
Finishing thoughts 125 thread: 2 counter: 7 thread: 1 counter: 8 thread: 2 counter: 8 thread: 1 counter: 9 thread: 2 counter: 9 THREAD 1 FINISHED. thread: 2 counter: 10 thread: 2 counter: 11 thread: 2 counter: 12 thread: 2 counter: 13 thread: 2 counter: 14 THREAD 2 FINISHED. Beautiful! Our threads alternate since they ... | 9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf |
Creating Our Own Fibers 126 When the OS signals that the data is ready, we would mark the thread as State::Ready to resume and the scheduler would resume execution just like in this example. While it requires a more sophisticated scheduler and infrastructure, I hope that you have gotten a good idea of how such a system... | 9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf |
Part 3: Futures and async/await in Rust This part will explain Futures and async/await in Rust from the ground up. Building upon the knowledge acquired thus far, we will construct a central example that will serve as a recurring theme in the subsequent chapters, eventually leading to the creation of a runtime capable o... | 9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf |
9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf | |
6 Futures in Rust In Chapter 5, we covered one of the most popular ways of modeling concurrency in a programming language: fibers/green threads. Fibers/green threads are an example of stackful coroutines. The other popular way of modeling asynchronous program flow is by using what we call stackless coroutines, and comb... | 9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf |
Futures in Rust 130 What is a future? A future is a representation of some operation that will be completed in the future. Async in Rust uses a poll-based approach in which an asynchronous task will have three phases: 1. The poll phase : A future is polled, which results in the task progressing until a point where it c... | 9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf |
A mental model of an async runtime 131 This is an example of a non-leaf future: let non_leaf = async { let mut stream = Tcp Stream::connect("127. 0. 0. 1:3000"). await. unwrap(); println!("connected!"); let result = stream. write(b"hello world\n"). await; println!("message sent!"); ... }; The two highlighted lines indi... | 9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf |
Futures in Rust 132 A fully working async system in Rust can be divided into three parts: Reactor (responsible for notifying about I/O events) Executor (scheduler) Future (a task that can stop and resume at specific points) So, how do these three parts work together? Let's take a look at a diagram that shows a simplifi... | 9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf |
What the Rust language and standard library take care of 133 In step 3, when the reactor gets a notification that an event has happened on one of the tracked sources, it locates the Waker associated with that source and calls Waker::wake on it. This will in turn inform the executor that the future is ready to make prog... | 9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf |
Futures in Rust 134 I/O vs CPU-intensive tasks As you know now, what you normally write are called non-leaf futures. Let's take a look at this async block using pseudo-Rust as an example: let non_leaf = async { let mut stream = Tcp Stream::connect("127. 0. 0. 1:3000"). await. unwrap(); // request a large dataset let re... | 9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf |
Summary 135 The third method is more of theoretical importance; normally, you' d be happy to send the task to the thread pool that most runtimes provide. Most executors have a way to accomplish #1 using methods such as spawn_blocking. These methods send the task to a thread pool created by the runtime where you can eit... | 9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf |
9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf | |
7 Coroutines and async/await Now that you've gotten a brief introduction to Rust's async model, it's time to take a look at how this fits in the context of everything else we've covered in this book so far. Rust's futures are an example of an asynchronous model based on stackless coroutines, and in this chapter, we'll ... | 9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf |
Coroutines and async/await 138 Remember to change the ports in the code if you for some reason have to change what port delayserver listens on. Introduction to stackless coroutines So, we've finally arrived at the point where we introduce the last method of modeling asynchronous operations in this book. Y ou probably r... | 9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf |
An example of hand-written coroutines 139 This has some advantages, which I've covered before, but the most prominent ones are that they're very efficient and flexible. The downside is that you' d never want to write these state machines by hand (you'll see why in this chapter), so you need some kind of support from th... | 9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf |
Coroutines and async/await 140 Therefore, our example will do the following: Avoid error handling. If anything fails, we panic. Be specific and not generic. Creating generic solutions introduces a lot of complexity and makes the underlying concepts harder to reason about since we consequently have to create extra abstr... | 9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf |
An example of hand-written coroutines 141 Futures module In futures. rs, the first thing we'll do is define a Future trait. It looks as follows: ch07/a-coroutine/src/future. rs pub trait Future { type Output; fn poll(&mut self)-> Poll State<Self::Output>; } If we contrast this with the Future trait in Rust's standard l... | 9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf |
Coroutines and async/await 142 HTTP module In this module, we'll implement a very simple HTTP client. This client can only make GET requests to our delayserver since we just use this as a representation of a typical I/O operation and don't care specifically about being able to do more than we need. The first thing we'l... | 9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf |
An example of hand-written coroutines 143 The first thing you'll notice in the function body is that there is not much happening here. We only return Http Get Future and that's it. In the function signature, you see that it returns an object implementing the Future trait that outputs a String when it's resolved. The st... | 9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf |
Coroutines and async/await 144 fn write_request(&mut self) { let stream = std::net::Tcp Stream::connect("127. 0. 0. 1:8080"). unwrap(); stream. set_nonblocking(true). unwrap(); let mut stream = mio::net::Tcp Stream::from_std(stream); stream. write_all(get_req(&self. path). as_bytes()). unwrap(); self. stream = Some(str... | 9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf |
An example of hand-written coroutines 145 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() == Error Kind::Would Block => { break Poll State::Not Ready; } Err(e) if e. kind() == Error Kind::Interrupted... | 9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf |
Coroutines and async/await 146 3. We get an error of kind Would Block. If that's the case, we know that since we set the stream to non-blocking, the data isn't ready yet or there is more data but we haven't received it yet. In that case, we return Poll State::Not Ready to communicate that more calls to the poll are nee... | 9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf |
An example of hand-written coroutines 147 poll them to completion one by one in the current design, the futures would not progress concurrently. Let that sink in for a moment. Languages such as Java Script start the operation when the coroutine is created, so there is no “one way” to do this. Every time you encounter a... | 9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf |
Coroutines and async/await 148 If we wrote our program as an async function, it would look as follows: async fn async_main() { println!("Program starting") let txt = Http::get("/1000/Hello World"). await; println!("{txt}"); let txt2 = Http::("500/Hello World2"). await; println!("{txt2}"); } In main. rs, start by making... | 9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf |
An example of hand-written coroutines 149 Wait1 : When we call Http::get, we get a Http Get Future returned that we store in the State enum. At this point, we return control back to the calling function so it can do other things if needed. We chose to make this generic over all Future functions that output a String, bu... | 9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf |
Coroutines and async/await 150 self. state = State::Wait1(fut); } State::Wait1(ref mut fut) => match fut. poll() { Poll State::Ready(txt) => { println!("{txt}"); let fut2 = Box::new(Http::get("/400/Hello World2")); self. state = State::Wait2(fut2); } Poll State::Not Ready => break Poll State::Not Ready, }, State::Wait2... | 9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf |
An example of hand-written coroutines 151 5. At this point, we change the state to State::Wait1 and we store the future we want to resolve so we can access it in the next state. 6. Our state machine has now changed its state from Start to Wait1. Since we're looping on the match statement, we immediately progress to the... | 9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf |
Coroutines and async/await 152 One thing to note here is that our main function is just a regular main function. The loop in our main function is what drives the asynchronous operations to completion: ch07/a-coroutine/src/main. rs fn main() { let mut future = async_main(); loop { match future. poll() { Poll State::Not ... | 9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf |
An example of hand-written coroutines 153 Schedule other tasks Schedule other tasks Schedule other tasks Schedule other tasks HTTP/1. 1 200 OK content-length: 11 connection: close content-type: text/plain; charset=utf-8 date: Tue, 24 Oct 2023 20:39:13 GMT Hello World2 By looking at the printouts, you can get an idea of... | 9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf |
Coroutines and async/await 154 Our state machine will be efficient, but that's pretty much it. However, you might also notice that there is a system to the craziness. This might not come as a surprise, but the code we wrote could be much simpler if we tagged the start of each function and each point we wanted to yield ... | 9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf |
async/await 155 So, let's take this a step further. To avoid confusion, and since our coroutines only yield to the calling function right now (there is no scheduler, event loop, or anything like that yet), we use a slightly different syntax called coroutine/wait and create a way to have these state machines generated f... | 9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf |
Coroutines and async/await 156 of the main goals is to take a look at the differences between the code we write and what it transforms into. In addition to that, macros can get quite complex to read and understand unless you work a lot with them on a regular basis. Instead, corofy is a normal Rust program you can find ... | 9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf |
async/await 157 We'll base the following examples on the exact same code as we did in the first one. In the repository, you'll find this example under ch07/b-async-await. If you write every example from the book and don't rely on the existing code in the repository, you can do one of two things: Keep changing the code ... | 9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf |
Coroutines and async/await 158 fn main() { let start = Instant::now(); let mut future = async_main(); loop { match future. poll() { Poll State::Not Ready => (), Poll State::Ready(_) => break, } } println!("\n ELAPSED TIME: {}", start. elapsed(). as_secs_f32()); } This code contains a few changes. First, we add a conven... | 9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf |
async/await 159 Wait2(Box<dyn Future<Output = String>>), Wait3(Box<dyn Future<Output = String>>), Wait4(Box<dyn Future<Output = String>>), Wait5(Box<dyn Future<Output = String>>), Resolved, } If you run the program using cargo run, you now get the following output: Program starting FIRST POLL-START OPERATION HTTP/1. 1 ... | 9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf |
Coroutines and async/await 160 date: Tue, xx xxx xxxx 21:06:05 GMT Hello World4 ELAPSED TIME: 10. 043025 So, you see that our code runs as expected. Since we called wait on every call to Http::get, the code ran sequentially, which is evident when we look at the elapsed time of 10 seconds. That makes sense since the del... | 9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf |
c-async-await—concurrent futures 161 This function takes a collection of futures as an argument and returns a Join All<F> future. The function simply creates a new collection. In this collection, we will have tuples consisting of the original futures we received and a bool value indicating whether the future is resolve... | 9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf |
Coroutines and async/await 162 We set Output to String. This might strike you as strange since we don't actually return anything from this implementation. The reason is that corofy will only work with futures that return a String (it's one of its many, many shortcomings), so we just accept that and return an empty stri... | 9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf |
c-async-await—concurrent futures 163 The main function will be the same, as well as the imports and declarations at the start of the file, so I'll only present the coroutine/await functions that we've changed: coroutine fn request(i: usize) { let path = format!("/{}/Hello World{i}", i * 1000); let txt = Http::get(&path... | 9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf |
Coroutines and async/await 164 If you run the program by writing cargo run, you should get the following output: Program starting FIRST POLL-START OPERATION FIRST POLL-START OPERATION FIRST POLL-START OPERATION FIRST POLL-START OPERATION FIRST POLL-START OPERATION HTTP/1. 1 200 OK content-length: 11 connection: close c... | 9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf |
Final thoughts 165 The thing to make a note of here is the elapsed time. It's now just over four seconds, just like we expected it would be when our futures run concurrently. If we take a look at how coroutine/await changed the experience of writing coroutines from a programmer's perspective, we'll see that we're much ... | 9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf |
Coroutines and async/await 166 Summary Good job! In this chapter, we introduced quite a bit of code and set up an example that we'll continue using in the following chapters. So far, we've focused on futures and async/await to model and create tasks that can be paused and resumed at specific points. We know this is a p... | 9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf |
8 Runtimes, Wakers, and the Reactor-Executor Pattern In the previous chapter, we created our own pausable tasks (coroutines) by writing them as state machines. We created a common API for these tasks by requiring them to implement the Future trait. We also showed how we can create these coroutines using some keywords a... | 9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf |
Runtimes, Wakers, and the Reactor-Executor Pattern 168 not one of those chapters you typically blaze through before going to bed, though, but I do promise it's absolutely worth it in the end. The chapter will be divided into the following segments: Introduction to runtimes and why we need them Improving our base exampl... | 9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf |
Introduction to runtimes and why we need them 169 Introduction to runtimes and why we need them As you know by now, you need to bring your own runtime for driving and scheduling asynchronous tasks in Rust. Runtimes come in many flavors, from the popular Embassy embedded runtime ( https://github. com/embassy-rs/embassy ... | 9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf |
Runtimes, Wakers, and the Reactor-Executor Pattern 170 An example of yielding to the OS scheduler is making a blocking call using the default std::net ::Tcp Stream or std::thread::sleep methods. Even potentially blocking calls using primitives such as Mutex provided by the standard library might yield to the OS schedul... | 9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf |
Improving our base example 171 be anything from a timer that expires, an interrupt if you write programs for embedded systems, or an I/O event such as a READABLE event on Tcp Stream. Y ou could have several kinds of reactors running in the same runtime. If the name executor gives you associations to executioners (the m... | 9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf |
Runtimes, Wakers, and the Reactor-Executor Pattern 172 2. Copy the future. rs and http. rs files in the src folder from the first project we created in Chapter 7, named a-coroutine (alternatively, copy the files from ch07/a-coroutine in the book's repository) to the src folder in our new project. 3. Make sure to add mi... | 9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf |
Improving our base example 173 This program is basically the same one we created in Chapter 7, only this time, we create it from our coroutine/wait syntax instead of writing the state machine by hand. Next, we need to transform this into code by using corofy since the compiler doesn't recognize our own coroutine/wait s... | 9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf |
Runtimes, Wakers, and the Reactor-Executor Pattern 174 The following diagram shows a simplified overview of our current design: Figure 8. 2-Executor and Future chain: current design If we take a closer look at the future chain, we can see that when a future is polled, it polls all its child futures until it reaches a l... | 9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf |
Improving our base example 175 The next diagram takes a closer look at the future chain and gives a simplified overview of how it works: Figure 8. 3-Future chain: a detailed view The first improvement we'll make is to avoid the need for continuous polling of our top-level future to drive it forward. | 9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf |
Runtimes, Wakers, and the Reactor-Executor Pattern 176 We'll change our design so that it looks more like this: Figure 8. 4-Executor and Future chain: design 2 In this design, we use the knowledge we gained in Chapter 4, but instead of simply relying on epoll, we'll use mio 's cross-platform abstraction instead. The wa... | 9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf |
Improving our base example 177 Changing the current implementation Now that we have an overview of our design and know what to do, we can go on and make the necessary changes to our program, so let's go through each file we need to change. We'll start with main. rs. main. rs We already made some changes to main. rs whe... | 9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf |
Runtimes, Wakers, and the Reactor-Executor Pattern 178 The next step is to create a static variable called REGISTRY. If you remember, Registry is the way we register interest in events with our Poll instance. We want to register interest in events on our Tcp Stream when making the actual HTTP GET request. We could have... | 9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf |
Improving our base example 179 Self { poll } } pub fn block_on<F>(&mut self, future: F) where F: Future<Output = String>, { let mut future = future; loop { match future. poll() { Poll State::Not Ready => { println!("Schedule other tasks\n"); let mut events = Events::with_capacity(100); self. poll. poll(&mut events, Non... | 9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.