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.

相关内容

热门资讯

王者定位怎么关安卓系统,轻松实... 你是不是也和我一样,对王者荣耀这款游戏爱得深沉呢?不过,有时候游戏里的设置让人头疼,比如安卓系统的王...
树莓派安卓系统流畅,打造便携式... 亲爱的读者们,你是否曾想过,将树莓派与安卓系统结合,会擦出怎样的火花呢?今天,就让我带你一起探索这个...
安卓系统智能机顶盒,引领家庭娱... 你有没有想过,家里的电视也能变得智能起来?没错,就是那个陪伴我们多年的老电视,现在也能摇身一变,成为...
安卓系统很差了吗现在,性能优劣... 最近是不是有不少朋友在讨论安卓系统的问题呢?有人说它越来越差了,也有人觉得它还是那个熟悉的“老朋友”...
安卓系统uc安装包,Andro... 你有没有发现,手机里的安卓系统越来越强大了?今天,咱们就来聊聊这个话题——安卓系统中的UC安装包。你...
安卓系统谷歌能删吗,谷歌能否删... 你有没有想过,那个一直陪伴你手机生活的安卓系统,它背后的谷歌爸爸,是不是也能被你随意删掉呢?这可不是...
安卓系统会不会更耗电,解析其功... 你有没有发现,手机用着用着,电池就有点不给力了?尤其是那些用安卓系统的手机,有时候感觉电就像流水一样...
安卓系统中无效目录,安卓系统无... 你有没有遇到过在安卓系统中,明明文件夹就在那里,但是就是找不到的情况?别急,今天就来给你揭秘安卓系统...
国产安卓机哪个系统好用,探寻最... 你有没有想过,国产安卓机哪个系统最好用呢?这可是个让人纠结的问题,毕竟每个系统都有它的特色和亮点。今...
安卓系统cpua9,引领性能与... 你有没有发现,最近你的安卓手机运行得是不是比以前顺畅多了?这可多亏了那个强大的安卓系统CPUA9啊!...
安卓系统usb驱动程序,功能、... 你有没有遇到过这种情况:手机里存了那么多宝贝照片和视频,想传输到电脑上保存,结果电脑却像个小顽皮,死...
安卓操作系统怎么关闭,轻松关闭... 手机里的安卓操作系统是不是有时候让你觉得有点儿烦呢?别急,今天就来手把手教你如何轻松关闭安卓操作系统...
追星手机壳推荐安卓系统,盘点热... 你有没有发现,现在追星族们对手机壳的热爱简直到了疯狂的地步?没错,就是那种能让你一秒变身偶像迷妹的手...
ios系统用安卓系统游戏下载软... 你有没有想过,明明是iOS系统的手机,却想玩安卓系统的游戏?这可不是什么天方夜谭,现在就有这么神奇的...
安卓高系统怎么用美化,打造专属... 亲爱的安卓用户们,你是不是也和我一样,对手机系统美化情有独钟呢?想要让你的安卓手机焕然一新,变得个性...
安卓系统怎么开夜间模式,安卓系... 亲爱的手机控们,你是不是在夜晚使用安卓手机时,眼睛感到有些不适?别担心,今天我要给你揭秘一个超级实用...
王者安卓系统用苹果人脸,一场视... 你知道吗?最近在手机圈里可是掀起了一股不小的波澜呢!那就是王者安卓系统竟然用上了苹果人脸识别技术!是...
安卓444怎么升级系统,轻松迈... 你那安卓444的小家伙是不是已经有点儿落伍了?别急,今天就来给你详细说说怎么给它来个系统升级,让它焕...
安卓系统raw修图软件,探索安... 你有没有发现,手机拍照越来越方便了,但有时候拍出来的照片还是不够完美呢?别急,今天就来给你安利几款安...
安卓系统的王者切换苹果,从安卓... 你知道吗?最近身边的朋友圈里掀起了一股热潮,那就是安卓系统的王者们纷纷切换到苹果阵营。这可真是让人大...