Rust You Don’t Know
admin
2024-01-30 00:48:32
0

Rust语言作为一种强调性能、安全和并发性的新的编程语言,正日益受到程序员们的关注。Rust语言已经连续7年蝉联 StackOverflow网站(全球最大的编程问答网站)最受欢语言。甚至Linus Torvalds认为Rust即将成为Linux的官方第二语言。有理由相信越来越多的程序员将加入尝试学习Rust。但Rust语言的学习曲线比较陡峭,门槛不低。因此,达坦科技的联合创始人兼CTO施继成将自己学习和运用Rust语言的心得体会集结成书,我们也将在达坦科技(DatenLord)公众号陆续连载。

这些思想的火花将不同于市面上其他关于学习Rust编程语言的教科书,它更多地将向程序员分享学习Rust语言的基本要义,以及在实际使用场景下如何运用Rust解决问题的思考,从而让Rust真正变成一种活生生的、有呼吸的、有用的语言。

本文是Rust You Don’t Know的第一章。

Chapter One: Process, Thread, and Coroutine

Before we start discussing the asynchronization of Rust, we'd better firstly talk about how the operating system organizes and schedules the tasks, which will help us understand the motivation of the language-level asynchronization mechanisms.

Process and thread

People always want to run multiple tasks simultaneously on the OS even though there's only one CPU core because one task usually can't occupy the whole CPU core at most times. Following the idea, we have to answer two questions to get the final design, how to abstract the task and how to schedule the tasks on the hardware CPU core.

Usually, we don't want tasks to affect each other, which means they can run separately and manage their states. As states are stored in the memory, tasks must hold their own memory space to achieve the above goal. For instance, the execution flow is a kind of in-memory state, recording the current instruction position and the on-stack states. In one word, processes are tasks having separated memory spaces on Linux.

Though memory space separation is one of the key features of processes, they sometimes have to share some memory. First, the kernel code is the same across all processes, kernel part memory space sharing reduces unnecessary memory redundant. Secondly, processes need to cooperate so that inter-process communications (IPC) are unavoidable, and most high-performance IPCs are some kind of memory sharing/transferring. Considering the above requirements sharing the whole memory space across tasks is more convenient in some scenarios, where thread helps.

A process can contain one (single-thread process) or more threads. Threads in a process share the same memory space, which means most state changes are observable by all these threads except for the execution stacks. Each thread has its execution flow and can run on any CPU core concurrently.

Now we know that process and thread are the basic execution units/tasks on most OSes, let's try to run them on the real hardware, CPU cores.

Schedule

The first challenge we meet when trying to run processes and threads is the limited hardware resources, the CPU core number is limited. When I write this section, one x86 CPU can at most run 128 tasks at the same time, AMD Ryzen™ Threadripper™ PRO 5995WX Processor. But it's too easy to create thousands of processes or threads on Linux, we have to decide how to place them on the CPU core and when to stop a task, where OS task scheduler helps.

Schedulers can interrupt an executing task regardless of its state, and schedule a new one. It's called preemptive schedule and is used by most OSes like Linux. The advantage is that it can share the CPU time slice between tasks fairly no matter what they're running, but the tasks have no idea about the scheduler. To interrupt a running task, hardware interruption like time interruption is necessary.

The other schedulers are called non-preemptive schedulers, which have to cooperate with the task while scheduling. Here tasks are not interrupted, instead, they decide when to release the computing resource. The tasks usually schedule themselves out when doing I/O operations, which usually take a while to complete. Fairness is hard to be guaranteed as the task itself may run forever without stopping, in which case other tasks have no opportunity to be scheduled on that core.

No matter what kind of scheduler is taken, tasks scheduling always needs to do the following steps:

  • Store current process/thread execution flow information.
  • Change page table mapping (memory space) and flush TLB if necessary.
  • Restore the new process/thread execution flow from the previously stored state.

After adopting a scheduler operating system can run tens of thousands of processes/threads on the limited hardware resource.

Coroutine

We have basic knowledge of OS scheduling, and it seems to work fine in most cases. Next, let's see how it performs in extreme scenarios. Free software developer, Jim Blandy, did an interesting test to show how much time it takes to do a context switch on Linux. In the test, the app creates 500 thread and connect them with pipes like a chain, and then pass a one-byte message from one side to the other side. The whole test runs 10000 iterations to get a stable result. The result shows that a thread context switch takes around 1.7us, compared to 0.2us of a Rust async task switch.

It's the first time to mention "Rust async task", which is a concrete implementation of coroutine in Rust. The coroutines are lightweight tasks for non-preemptive multitasking, whose execution can be suspended and resumed. Usually, the task itself decides when to suspend and wait for a notification to resume. To suspend and resume tasks' execution flow, the execution states should be saved, just like what OS does. Saving the CPU register values is easy for the OS, but not for the applications. Rust saves it to a state machine, and the machine can only be suspended and resumed from the valid states in that machine. To make it easy, We name the state machine "Future".

Future

We all know that the Future is the data structure returned from an async function, an async block is also a future. When we get it, it does nothing, it's just a plan and a blueprint, telling us what it's going to do. Let's see the example below:

async fn async_fn() -> u32 {return 0;
}

We can't see any "Future" structure in the function definition, but the compiler will translate the function signature to another one returning a "Future":

fn async_fn() -> Future {
...
}

Rust compiler does us a great favor to generate the state machine for us. Here's the Futures API from std lib:

pub trait Future {type Output;fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll;
}pub enum Poll {Ready(T),Pending,
}

The poll function tries to drive the state machine until a final result Output is returned. The state machine is a black box for the caller of the poll function, since that Poll::Pending means it's not in the final state, and Poll::Ready(T) means it's in the final state. Whenever the Poll::Pending is returned it means the coroutine is suspended. Every call to poll is trying to resume the coroutine.

Runtime

Since Futures are state machines, there should be a driver that pushes the machine state forward. Though we can write the driver manually by polling the Futures one by one until we get the final result, that work should be done once and reused everywhere, in the result the runtime comes. A Rust async runtime handles the following tasks:

  1. Drive the received Futures forward.
  2. Park or store the blocked Futures.
  3. Get notification to restore or resume the blocked Futures.

Summary

In this chapter, we learned that "Rust async" is a way to schedule tasks. And the execution state is stored in a state machine named Future. In the next chapters, we'll discuss Futureautomatical generation by the compiler and its optimizations.

相关内容

热门资讯

安卓系统用的华为应用,探索智能... 你知道吗?在安卓系统里,华为的应用可是个宝库呢!它们不仅功能强大,而且使用起来超级方便。今天,就让我...
安卓变ios系统魅蓝 你知道吗?最近有个朋友突然告诉我,他要把自己的安卓手机换成iOS系统,而且还是魅蓝品牌的!这可真是让...
幻书启世录安卓系统,安卓世界中... 亲爱的读者们,你是否曾在某个夜晚,被一本神奇的书所吸引,仿佛它拥有着穿越时空的力量?今天,我要带你走...
电脑安装安卓系统进不去,安卓系... 电脑安装安卓系统后竟然进不去,这可真是让人头疼的问题啊!你是不是也遇到了这种情况,心里直呼“怎么办怎...
用键盘切换控制安卓系统,畅享安... 你有没有想过,用键盘来控制你的安卓手机?是的,你没听错,就是那个我们每天敲敲打打的小玩意儿——键盘。...
小米安卓镜像系统在哪,小米安卓... 你有没有想过,你的小米手机里有一个隐藏的宝藏——安卓镜像系统?没错,就是那个可以让你的手机瞬间变身成...
安卓手机下载排班系统,高效排班... 你有没有想过,每天忙碌的工作中,有没有什么好帮手能帮你轻松管理时间呢?今天,就让我来给你介绍一个超级...
桌面组件如何弄安卓系统,桌面组... 亲爱的桌面爱好者们,你是否曾梦想过将安卓系统搬到你的电脑桌面上?想象那些流畅的动画、丰富的应用,还有...
安卓13系统介绍视频,新功能与... 亲爱的读者们,你是否对安卓13系统充满好奇?想要一探究竟,却又苦于没有足够的时间去研究?别担心,今天...
车机安卓7.1系统,功能升级与... 你有没有发现,现在的车机系统越来越智能了?尤其是那些搭载了安卓7.1系统的车机,简直就像是个贴心的智...
安卓系统下如何读pdf,And... 你有没有遇到过这种情况:手机里存了一大堆PDF文件,可是怎么也找不到一个能顺畅阅读的工具?别急,今天...
安卓系统全国通用的吗,畅享智能... 你有没有想过,为什么你的手机里装的是安卓系统呢?安卓系统,这个名字听起来是不是有点神秘?今天,就让我...
假苹果手机8安卓系统,颠覆传统... 你有没有想过,如果苹果手机突然变成了安卓系统,会是怎样的景象呢?想象那熟悉的苹果外观,却运行着安卓的...
安卓12.0系统vivo有吗,... 你有没有听说最近安卓系统又升级啦?没错,就是那个让手机焕然一新的安卓12.0系统!那么,咱们国内的手...
核心芯片和安卓系统,探索核心芯... 你知道吗?在科技的世界里,有一对“黄金搭档”正悄悄改变着我们的生活。他们就是——核心芯片和安卓系统。...
如何调安卓系统屏幕颜色,安卓系... 亲爱的手机控们,你是否曾觉得安卓系统的屏幕颜色不够个性,或者是因为长时间盯着屏幕而感到眼睛疲劳?别担...
旧台式电脑安装安卓系统,轻松安... 你那台旧台式电脑是不是已经服役多年,性能逐渐力不从心,却又不忍心让它退役呢?别急,今天就来教你怎么给...
美国要求关闭安卓系统,科技霸权... 美国要求关闭安卓系统:一场技术革新还是政治博弈?在数字化时代,智能手机已经成为我们生活中不可或缺的一...
安卓系统日记本 你有没有发现,手机里的安卓系统日记本,简直就是记录生活点滴的宝藏库呢?想象每天忙碌的生活中,有没有那...
安卓手机广告最少的系统,探索安... 你有没有发现,用安卓手机的时候,广告总是无处不在,让人烦得要命?不过别急,今天我要给你揭秘一个秘密—...