text stringlengths 0 3.16k | source stringclasses 1
value |
|---|---|
9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf | |
Asynchronous Programming in Rust Learn asynchronous programming by building working examples of futures, green threads, and runtimes Carl Fredrik Samson | 9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf |
Asynchronous Programming in Rust Copyright © 2024 Packt Publishing All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical art... | 9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf |
To my family—my brother, my parents, and especially my beloved wife and fantastic children that make every day an absolute joy.-Carl Fredrik Samson | 9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf |
Contributors About the author Carl Fredrik Samson is a popular technology writer and has been active in the Rust community since 2018. He has an MSc in Business Administration where he specialized in strategy and finance. When not writing, he's a father of two children and a CEO of a company with 300 employees. He's be... | 9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf |
About the reviewer Evgeni Pirianov is an experienced Senior Software Engineer with a deep expertise in Backend Technologies, Web3 an Blockchain. Evgeni has graduated with a degree in Engineering from Imperial College, London and has worked for a few years developing non-linear solvers in C++. Ever since, he has been at... | 9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf |
9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf | |
Preface xiii Part 1: Asynchronous Programming Fundamentals 1 Concurrency and Asynchronous Programming: a Detailed Overview 3 Technical requirements 4 An evolutionary journey of multitasking 4 Non-preemptive multitasking 4 Preemptive multitasking 5 Hyper-threading 5 Multicore processors 6 Do you really write synchronous... | 9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf |
Table of Contents viii 2 How Programming Languages Model Asynchronous Program Flow 25 Definitions 26 Threads 27 Threads provided by the operating system 29 Creating new threads takes time 29 Each thread has its own stack 29 Context switching 30 Scheduling 30 The advantage of decoupling asynchronous operations from OS t... | 9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf |
Table of Contents ix Part 2: Event Queues and Green Threads 4 Create Your Own Event Queue 65 Technical requirements 65 Design and introduction to epoll 66 Is all I/O blocking? 72 The ffi module 73 Bitflags and bitmasks 76Level-triggered versus edge-triggered events 78 The Poll module 81 The main program 84 Summary 93 5... | 9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf |
Table of Contents x What the Rust language and standard library take care of 133I/O vs CPU-intensive tasks 134 Summary 135 7 Coroutines and async/await 137 Technical requirements 137 Introduction to stackless coroutines 138 An example of hand-written coroutines 139 Futures module 141 HTTP module 142 Do all futures have... | 9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf |
Table of Contents xi 9 Coroutines, Self-Referential Structs, and Pinning 213 Technical requirements 214 Improving our example 1-variables 214 Setting up the base example 215 Improving our base example 217 Improving our example 2-references 222 Improving our example 3-this is... not... good... 227 Discovering self-refer... | 9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf |
9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf | |
Preface The content in this book was initially written as a series of shorter books for programmers wanting to learn asynchronous programming from the ground up using Rust. I found the existing material I came upon at the time to be in equal parts frustrating, enlightening, and confusing, so I wanted to do something ab... | 9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf |
Preface xiv I want this book to feel like you're joining me on a journey, where we build our knowledge topic by topic and learn by creating examples and experiments along the way. I don't want this book to feel like a lecturer simply telling you how everything works. This book is created for people who are curious by n... | 9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf |
Preface xv Chapter 4, Create Your Own Event Queue, is the chapter where you create your own event queue that mimics the API of mio (the popular Rust library that underpins much of the current async ecosystem). The example will center around epoll and go into quite a bit of detail on how it works. Chapter 5, Creating Ou... | 9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf |
Preface xvi The ideal way to read this book is to have the book and a code editor open side by side. Y ou should also have the accompanying repository available so you can refer to that if you encounter any issues. Software/hardware covered in the book Operating system requirements Rust (version 1. 51 or later) Windows... | 9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf |
Preface xvii Conventions used There are a number of text conventions used throughout this book. Code in text : Indicates code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles. Here is an example: “So, now we have created our own async ... | 9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf |
Preface xviii Piracy : If you come across any illegal copies of our works in any form on the internet, we would be grateful if you would provide us with the location address or website name. Please contact us at copyright@packt. com with a link to the material. If you are interested in becoming an author : If there is ... | 9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf |
Preface xix Download a free PDF copy of this book Thanks for purchasing this book! Do you like to read on the go but are unable to carry your print books everywhere? Is your e Book purchase not compatible with the device of your choice? Don't worry, now with every Packt book you get a DRM-free PDF version of that book ... | 9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf |
9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf | |
Part 1: Asynchronous Programming Fundamentals In this part, you'll receive a thorough introduction to concurrency and asynchronous programming. We'll also explore various techniques that programming languages employ to model asynchrony, examining the most popular ones and covering some of the pros and cons associated w... | 9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf |
9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf | |
1 Concurrency and Asynchronous Programming: a Detailed Overview Asynchronous programming is one of those topics many programmers find confusing. Y ou come to the point when you think you've got it, only to later realize that the rabbit hole is much deeper than you thought. If you participate in discussions, listen to e... | 9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf |
Concurrency and Asynchronous Programming: a Detailed Overview 4 There's not a lot of code in this chapter, so we're off to a soft start. It's a good time to make a cup of tea, relax, and get comfortable, as we're about start this journey together. Technical requirements All examples will be written in Rust, and you hav... | 9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf |
An evolutionary journey of multitasking 5 Besides offloading a huge responsibility to every programmer writing a program for your platform, this method was naturally error-prone. A small mistake in a program's code could halt or crash the entire system. Note Another popular term for what we call non-preemptive multitas... | 9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf |
Concurrency and Asynchronous Programming: a Detailed Overview 6 example, when an operation only required some parts of the CPU, an instruction could be run on the ALU simultaneously. This became the start of hyper-threading. Y our computer today, for example, may have 6 cores and 12 logical cores.. This is exactly wher... | 9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf |
Concurrency versus parallelism 7 Note *However, modern CPUs can also do a lot of things in parallel. Most CPUs are pipelined, meaning that the next instruction is loaded while the current one is executing. It might have a branch predictor that tries to figure out what instructions to load next. The processor can also r... | 9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf |
Concurrency and Asynchronous Programming: a Detailed Overview 8 Figure 1. 1-Multitasking two tasks First, we need to agree on some definitions: Resource : This is something we need to be able to progress a task. Our resources are limited. This could be CPU time or memory. Task : This is a set of operations that require... | 9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf |
Concurrency versus parallelism 9 Note It doesn't help that concurrent is defined in the dictionary as operating or occurring at the same time, which doesn't really help us much when trying to describe how it differs from parallel. For me, this first clicked when I started to understand why we want to make a distinction... | 9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf |
Concurrency and Asynchronous Programming: a Detailed Overview 10 Well, even though your bartender is very fast at taking new orders, they can only serve 30 customers an hour. Remember, they're waiting for 100 seconds while the beer settles and they're practically just standing there, and they only use 20 seconds to act... | 9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf |
Concurrency versus parallelism 11 served in the shortest amount of time possible, letting customers leave the bar with their beer faster and giving space to customers who want to make a new order. Now, this way, you can increase throughput even further. Y ou still won't reach the theoretical maximum, but you'll get ver... | 9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf |
Concurrency and Asynchronous Programming: a Detailed Overview 12 What about threads provided by the operating system? We'll cover threads a bit more when we talk about strategies for handling I/O later in this book, but I'll mention them here as well. One challenge when using OS threads to understand concurrency is tha... | 9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf |
The role of the operating system 13 In an effort to make the definitions as distinct as possible, we'll define these terms more narrowly than you' d normally see. However, just be aware that we can't please everyone and we do this for our own sake of making the subject easier to understand. On the other hand, if you fa... | 9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf |
Concurrency and Asynchronous Programming: a Detailed Overview 14 Note This is not as simple when we're talking about modern machines with 4, 6, 8, or 12 physical cores, since you might actually execute code on one of the CPUs uninterrupted if the system is under very little load. The important part here is that you can... | 9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf |
The CPU and the operating system 15 However, a syscall is not the only way we interact with our operating system, as we'll see in the following section. The CPU and the operating system Does the CPU cooperate with the operating system? If you had asked me this question when I first thought I understood how programs wor... | 9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf |
Concurrency and Asynchronous Programming: a Detailed Overview 16 and instead of simply copying the memory address itself to {0}, it will fetch what's at that memory location and move it over. Anyway, we're just writing instructions to the CPU here. No standard library, no syscall; just raw instructions. There is no way... | 9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf |
The CPU and the operating system 17 We'll cover the first one here and the second in the next section. How does the CPU prevent us from accessing memory we're not supposed to access? As I mentioned, modern CPU architectures define some basic concepts by design. Some examples of this are as follows: Virtual memory Page ... | 9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf |
Concurrency and Asynchronous Programming: a Detailed Overview 18 But can't we just change the page table in the CPU? Now, this is where the privilege level comes in. Most modern operating systems operate with two ring levels : ring 0, the kernel space, and ring 3, the user space. Figure 1. 2-Privilege rings Most CPUs h... | 9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf |
Interrupts, firmware, and I/O 19 Interrupts, firmware, and I/O We're nearing the end of the general CS subjects in this book, and we'll start to dig our way out of the rabbit hole soon. This part tries to tie things together and look at how the whole computer works as a system to handle I/O and concurrency. Let's get t... | 9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf |
Concurrency and Asynchronous Programming: a Detailed Overview 20 Step 2-Registering events with the OS This is handled in one of three ways: 1. We tell the operating system that we're interested in Read events but we want to wait for it to happen by yielding control over our thread to the OS. The OS then suspends our t... | 9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf |
Interrupts, firmware, and I/O 21 Step 5-Interrupt handler The IDT is a table where the OS (or a driver) registers handlers for different interrupts that may occur. Each entry points to a handler function for a specific interrupt. The handler function for a network card would typically be registered and handled by a dri... | 9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf |
Concurrency and Asynchronous Programming: a Detailed Overview 22 Interrupts As you know by now, there are two kinds of interrupts: Hardware interrupts Software interrupts They are very different in nature. Hardware interrupts Hardware interrupts are created by sending an electrical signal through an IRQ. These hardware... | 9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf |
Summary 23 Summary This chapter covered a lot of ground, so good job on doing all that legwork. We learned a little bit about how CPUs and operating systems have evolved from a historical perspective and the difference between non-preemptive and preemptive multitasking. We discussed the difference between concurrency a... | 9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf |
9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf | |
2 How Programming Languages Model Asynchronous Program Flow In the previous chapter, we covered asynchronous program flow, concurrency, and parallelism in general terms. In this chapter, we'll narrow our scope. Specifically, we'll look into different ways to model and deal with concurrency in programming languages and ... | 9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf |
How Programming Languages Model Asynchronous Program Flow 26 Callback based approaches Promises, futures, and async/await Definitions We can broadly categorize abstractions over concurrent operations into two groups: 1. Cooperative : These are tasks that yield voluntarily either by explicitly yielding or by calling a f... | 9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf |
Definitions 27 Note In a system where the scheduler can pre-empt running tasks, tasks can also yield voluntarily as they do in a cooperative system, and it's rare with a system that only relies on pre-emption. We can further divide these abstractions into two broad categories based on the characteristics of their imple... | 9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf |
How Programming Languages Model Asynchronous Program Flow 28 of this is that most CPUs assume that there is a stack it can perform operations on and that it has a register for the stack pointer and instructions for stack manipulation. User-level threads can, in their broadest sense, refer to any implementation of a sys... | 9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf |
Threads provided by the operating system 29 Threads provided by the operating system Note! We call this 1:1 threading. Each task is assigned one OS thread. Since this book will not focus specifically on OS threads as a way to handle concurrency going forward, we treat them more thoroughly here. Let's start with the obv... | 9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf |
How Programming Languages Model Asynchronous Program Flow 30 to be configured, they're still fixed in size and can't grow or shrink. They are, after all, the cause of stack overflows, which will be a problem if you configure them to be too small for the tasks you're running. If we have many small tasks that only requir... | 9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf |
Threads provided by the operating system 31 The advantage of decoupling asynchronous operations from OS threads Decoupling asynchronous operations from the concept of threads has a lot of benefits. First of all, using OS threads as a means to handle concurrency requires us to use what essentially is an OS abstraction t... | 9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf |
How Programming Languages Model Asynchronous Program Flow 32 ch02/aa-os-threads use std::thread::{self, sleep}; fn main() { println!("So, we start the program here!"); let t1 = thread::spawn(move || { sleep(std::time::Duration::from_millis(200)); println!("The long running tasks finish last!"); }); let t2 = thread::spa... | 9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf |
Fibers and green threads 33 Fibers and green threads Note! This is an example of M:N threading. Many tasks can run concurrently on one OS thread. Fibers and green threads are often referred to as stackful coroutines. The name “green threads” originally stems from an early implementation of an M:N threading model used i... | 9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf |
How Programming Languages Model Asynchronous Program Flow 34 The typical flow goes as follows: Y ou run some non-blocking code Y ou make a blocking call to some external resource The CPU jumps to the main thread, which schedules a different thread to run and jumps to that stack Y ou run some non-blocking code on the ne... | 9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf |
Fibers and green threads 35 The first solution sounds pretty simple, as you can leave the original stack as it is, and you can basically context switch over to the new stack when needed and continue from there. However, modern CPUs can work extremely fast if they can work on a contiguous piece of memory due to caching ... | 9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf |
How Programming Languages Model Asynchronous Program Flow 36 One unexpected downside of this is that most OS schedulers make sure all threads get some time to run by giving each OS thread a time slice where it can run before the OS pre-empts the thread and schedules a new thread on that CPU. A program using many OS thr... | 9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf |
Callback based approaches 37 Callback based approaches Note! This is another example of M:N threading. Many tasks can run concurrently on one OS thread. Each task consists of a chain of callbacks. Y ou probably already know what we're going to talk about in the next paragraphs from Java Script, which I assume most know... | 9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf |
How Programming Languages Model Asynchronous Program Flow 38 Sharing state between tasks is difficult due to the complexity of ownership rules. Debugging callbacks can be difficult. Coroutines: promises and futures Note! This is another example of M:N threading. Many tasks can run concurrently on one OS thread. Each ta... | 9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf |
Coroutines: promises and futures 39 The latter approach is also referred to as the continuation-passing style. Each subtask calls a new one once it's finished. The difference between callbacks and promises is even more substantial under the hood. Y ou see, promises return a state machine that can be in one of three sta... | 9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf |
How Programming Languages Model Asynchronous Program Flow 40 When using Rust, you can see the same transformation happening with the function signature when you write something such as this: async fn run()-> () {... } The function wraps the return object, and instead of returning the type (), it returns a Future with a... | 9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf |
Summary 41 It can be implemented in a very memory-efficient way It's easy to implement for various platforms Drawbacks Pre-emption can be hard, or impossible, to fully implement, as the tasks can't be stopped in the middle of a stack frame It needs compiler support to leverage its full advantages Debugging can be diffi... | 9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf |
9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf | |
3 Understanding OS-Backed Event Queues, System Calls, and Cross-Platform Abstractions In this chapter, we'll take a look at how an OS-backed event queue works and how three different operating systems handle this task in different ways. The reason for going through this is that most async runtimes I know of use OS-back... | 9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf |
Understanding OS-Backed Event Queues, System Calls, and Cross-Platform Abstractions 44 abstractions might seem a bit unintuitive if you only have a high-level overview of how, for example, IOCP works on Windows. The reason for this is that these abstractions need to provide one API that covers the fact that different o... | 9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf |
Why use an OS-backed event queue? 45 This chapter is a little special since we build some basic understanding from the ground up, which means some of it is quite low-level and requires a specific operating system and CPU family to run. Don't worry; I've chosen the most used and popular CPU, so this shouldn't be a probl... | 9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf |
Understanding OS-Backed Event Queues, System Calls, and Cross-Platform Abstractions 46 I/O operations need to go through the operating system since they are dependent on resources that our operating system abstracts over. This can be the disk drive, the network card, or other peripherals. Especially in the case of netw... | 9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf |
Readiness-based event queues 47 Event queuing via epoll/kqueue and IOCP This is a sort of hybrid of the previous approaches. In the case of a network call, the call itself will be non-blocking. However, instead of polling the handle regularly, we can add that handle to an event queue, and we can do that with thousands ... | 9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf |
Understanding OS-Backed Event Queues, System Calls, and Cross-Platform Abstractions 48 6. We call read on the socket we created in step 2. Figure 3. 1-A simplified view of the epoll and kqueue flow Completion-based event queues IOCP stands for input/output completion port. This is a completion-based event queue. This t... | 9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf |
epoll, kqueue, and IOCP 49 5. Our thread is unblocked and our buffer is now filled with the data we're interested in. Figure 3. 2-A simplified view of the IOCP flow epoll, kqueue, and IOCP epoll is the Linux way of implementing an event queue. In terms of functionality, it has a lot in common with kqueue. The advantage... | 9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf |
Understanding OS-Backed Event Queues, System Calls, and Cross-Platform Abstractions 50 Lending out a buffer to the OS also provides some challenges since it's very important that this buffer stays untouched while waiting for an operation to return. Windows Linux mac OS IOCP epoll kqueue Completion based Readiness based... | 9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf |
System calls, FFI, and cross-platform abstractions 51 If you wanted to present a readiness-based API instead, you have to create an illusion of having two separate operations when doing I/O on Windows. First, request a notification when the data is ready to be read on a socket, and then actually read the data. While po... | 9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf |
Understanding OS-Backed Event Queues, System Calls, and Cross-Platform Abstractions 52 Raw syscall on Linux On Linux and mac OS, the syscall we want to invoke is called write. Both systems operate based on the concept of file descriptors, and stdout is already present when you start a process. If you don't run Linux on... | 9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf |
System calls, FFI, and cross-platform abstractions 53 First, we have an attribute named #[inline(never)] that tells the compiler that we never want this function to be inlined during optimization. Inlining is when the compiler omits the function call and simply copies the body of the function instead of calling it. In ... | 9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf |
Understanding OS-Backed Event Queues, System Calls, and Cross-Platform Abstractions 54 If you run this on Linux, you should now see the following message in your console: Hello world from raw syscall! Raw syscall on mac OS Now, since we use instructions that are specific to the CPU architecture, we'll need different fu... | 9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf |
System calls, FFI, and cross-platform abstractions 55 Aside from different register naming, there is not that much difference from the one we wrote for Linux, with the exception of the fact that a write operation has the code 4 on mac OS instead of 1 as it did on Linux. Also, the CPU instruction that issues a software ... | 9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf |
Understanding OS-Backed Event Queues, System Calls, and Cross-Platform Abstractions 56 let message = "Hello world from syscall!\n"; let message = String::from(message); syscall(message). unwrap(); } The only difference is that instead of pulling in the asm module, we pull in the io module. Using the OS-provided API in ... | 9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf |
System calls, FFI, and cross-platform abstractions 57 extern "C" (sometimes written without the "C", since "C" is assumed if nothing is specified) means we want to use the "C" calling convention when calling the function write in the "C" library we're linking to. This function needs to have the exact same name as the f... | 9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf |
Understanding OS-Backed Event Queues, System Calls, and Cross-Platform Abstractions 58 Y ou'll probably be familiar with the first two lines now, as they're the same as we wrote for our raw syscall example. We get the pointer to the buffer where our text is stored and the length of that buffer. Next is our call to the ... | 9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf |
System calls, FFI, and cross-platform abstractions 59 h Console Output: i32, lp Buffer: *const u16, number Of Chars To Write: u32, lp Number Of Chars Written: *mut u32, lp Reserved: *const std::ffi::c_void, )-> i32; } The first thing you notice is that we no longer link to the "C" library. Instead, we link to the kerne... | 9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf |
Understanding OS-Backed Event Queues, System Calls, and Cross-Platform Abstractions 60 msg_ptr, len, &mut output, std::ptr::null() )}; if res == 0 { return Err(io::Error::last_os_error()); } Ok(()) } The first thing we do is convert the text to utf-16-encoded text, which Windows uses. Fortunately, Rust has a built-in f... | 9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf |
Summary 61 The highest level of abstraction This is simple, but I wanted to add this just for completeness. Rust standard library wraps the calls to the underlying OS APIs for us, so we don't have to care about what syscalls to invoke. fn main() { println!("Hello world from the standard library"); } Congratulations! Y ... | 9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf |
9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf | |
Part 2: Event Queues and Green Threads In this part, we'll present two examples. The first example demonstrates the creation of an event queue using epoll. We will design the API to closely resemble the one used by mio, allowing us to grasp the fundamentals of both mio and epoll. The second example illustrates the use ... | 9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf |
9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf | |
4 Create Y our Own Event Queue In this chapter, we'll create a simple version of an event queue using epoll. We'll take inspiration from mio (https://github. com/tokio-rs/mio ), a low-level I/O library written in Rust that underpins much of the Rust async ecosystem. Taking inspiration from mio has the added benefit of ... | 9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf |
Create Your Own Event Queue 66 If you're on Windows, my recommendation is to set up WSL (https://learn. microsoft. com/en-us/windows/wsl/install ), if you haven't already, and install Rust on the Linux operating system running on WSL. If you're using Mac, you can create a virtual machine (VM) running Linux, for example... | 9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf |
Design and introduction to epoll 67 As I mentioned at the start of this chapter, we'll take our inspiration from mio. This has one big upside and one downside. The upside is that we get a gentle introduction to how mio is designed, making it much easier to dive into that code base if you want to learn more than what we... | 9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf |
Create Your Own Event Queue 68 In this example, we'll divide the project into a few modules, and we'll split the code up into the following files: src |--ffi. rs |--main. rs |--poll. rs Their descriptions are as follows: ffi. rs : This module will contain the code related to the syscalls we need to communicate with the... | 9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf |
Design and introduction to epoll 69 } pub fn registry(&self)-> &Registry { &self. registry } pub fn poll(&mut self, events: &mut Events, timeout: Option<i32>)-> Result<()> { todo!() } } pub struct Registry { raw_fd: i32, } impl Registry { pub fn register(&self, source: &Tcp Stream, token: usize, interests: i32)-> Resul... | 9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf |
Create Your Own Event Queue 70 Poll is a struct that represents the event queue itself. It has a few methods: new : Creates a new event queue registry : Returns a reference to the registry that we can use to register interest to be notified about new events poll : Blocks the thread it's called on until an event is read... | 9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf |
Design and introduction to epoll 71 Registry implements one important method we won't implement in our example, called try_clone. The reason we won't implement this is that we don't need it to understand how an event loop like this works and we want to keep the example simple and easy to understand. However, this metho... | 9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf |
Create Your Own Event Queue 72 Is all I/O blocking? Finally, a question that's easy to answer. The answer is a big, resounding... maybe. The thing is that not all I/O operations will block in the sense that the operating system will park the calling thread and it will be more efficient to switch to another task. The re... | 9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf |
The ffi module 73 While its scope is larger than mio (which only cares about non-blocking I/O), libuv is to Node in Java Script what mio is to Tokio in Rust. Note The reason for doing file I/O in a thread pool is that there have historically been poor cross-platform APIs for non-blocking file I/O. While it's true that ... | 9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf |
Create Your Own Event Queue 74 I'll get back to explaining what these constants are in a moment. Let's first take a look at the syscalls we need to make. Fortunately, we've already covered syscalls in detail, so you already know the basics of ffi and why we link to C in the preceding code: epoll_create is the syscall w... | 9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf |
The ffi module 75 The last part of the code in this file is the Event struct: ch04/a-epoll/src/ffi. rs #[derive(Debug)] #[repr(C, packed)] pub struct Event { pub(crate) events: u32, // Token to identify event pub(crate) epoll_data: usize, } impl Event { pub fn token(&self)-> usize { self. epoll_data } } This structure ... | 9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf |
Create Your Own Event Queue 76 What does #[repr(packed)] do? The #[repr(packed)] annotation is new to us. Usually, a struct will have padding either between fields or at the end of the struct. This happens even when we've specified #[repr(C)]. The reason has to do with efficient access to the data stored in the struct ... | 9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf |
The ffi module 77 An integer, such as i32, can be expressed as 32 bits. EPOLLIN has the hex value of 0x1 (which is simply 1 in decimal). Represented in bits, this would look like 000000000000000000000000 00000001. EPOLLET, on the other hand, has a value of 1 << 31. This simply means the bit representation of the decima... | 9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf |
Create Your Own Event Queue 78 10000000000000000000000000000001 read_event? true, edge_triggered: true, oneshot?: false The next topic we will introduce in this chapter is the concept of edge-triggered events, which probably need some explanation. Level-triggered versus edge-triggered events In a perfect world, we woul... | 9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf |
The ffi module 79 EPOLLONESHOT tells epoll that once we receive an event on this file descriptor, it should disable the file descriptor in the interest list. It won't remove it, but we won't get any more notifications on that file descriptor unless we explicitly reactivate it by calling epoll_ctl with the EPOLL_CTL_MOD... | 9781805128137-ASYNCHRONOUS_PROGRAMMING_IN_RUST.pdf |
End of preview. Expand in Data Studio
README.md exists but content is empty.
- Downloads last month
- 12