一个没有线程的操作系统:参与者模型
An OS with no threads: The Actor Model

原始链接: https://www.timdbg.com/posts/dbgos-actor-model/

作者描述了 DbgOS:这是一个从零开始用 Rust 编写的操作系统,尝试了一些非常规设计,尤其是在并发方面。DbgOS 不使用线程和共享内存,而是使用 actor:这些隔离实例拥有邮箱、类型化消息、私有状态和非阻塞处理函数。模块是带有生成模式元数据的 ELF 二进制文件;actor 定义 init/handle 函数,并使用回复槽位,使异步风格的任务能够以消息形式返回结果。操作系统禁止可写共享段、阻塞调用、同时处理消息以及长时间运行的处理函数。因此,系统中没有抢占、重入、共享可写内存,也不需要锁;CPU 密集型工作必须拆分成协作式异步片段。作者将其与大量使用线程的系统进行对比:在这类系统中,挂起的线程会消耗大量内存,并使 I/O 扩展变得复杂。尽管无线程 actor 需要手动管理状态,但它们很轻量,并实现了关键目标:在不丢失状态的情况下热替换模块。由于处理函数的执行有界、actor 能安全进入静默状态,并且所有持久化数据都有模式元数据,DbgOS 可以跨模块版本迁移状态。这使快速迭代,尤其是在使用 LLM 生成代码时,变得可行,并暗示了应用挂起、迁移和分布式 actor 等未来可能性。文章主张质疑操作系统的既有假设,并尝试奇怪的设计。

HN 讨论了一个围绕 actor 而非线程构建的实验性操作系统。评论者将这一想法与 1970 年代的 COBOL 队列/DAG 系统以及 CICS 事务监控器相比较,而另一些人则强调真正的 actor 系统有所不同:actor 拥有私有邮箱和隔离状态,以点对点方式通信,并可由运行时调度(如 Erlang/BEAM),而不是共享外部队列。大量争论围绕术语展开——队列、“非阻塞”、异步 future、协作式与抢占式调度——以及“无线程”究竟是指没有操作系统线程,还是没有采用共享状态的线程模型。怀疑者警告说,actor 会把每个问题都变成分布式问题:调试、背压、超时、部分 I/O 故障、CPU 密集型工作、多核扩展和重入性仍然很难处理。另一些人指出,协作式多任务处理在通用操作系统中的历史表现不佳,第三方应用也可能表现不当。支持者提到 Rust 的所有权转移/零拷贝消息传递、基于能力的寻址、嵌入式系统,以及 Erlang、Hubris、Midori、MMURTL 和 uFork 等既有系统。作者将其定位为一个受限且为特定用途构建的操作系统,而不是通用替代方案。
相关文章

原文

If you read my last post, you know that I’m making my own OS, DbgOS. If you haven’t read that, the short version is that I’m making an OS from scratch in Rust so I can try different ideas in OS design and learn new things by making strange choices. This time I want to talk about the decisions around how the OS deals with concurrency. Long the bane of our existence, concurrency bugs are hard to find, hard to analyze, and very easy to make. Over the past 50+ years, we’ve invented many schemes to completely avoid this class of bugs, and many of them revolve around eliminating shared state. One such model is the actor model, which originated in a 1973 paper by Carl Hewitt, Peter Bishop, and Richard Steiger. The unit of concurrency here is (unsurprisingly) an “actor”. Each actor operates independently, has its own mailbox, and can send messages to other actors, but cannot share data any other way. The actor model is often associated with Erlang, although the Erlang designers weren’t explicitly drawing on this paper as a reference. But it did show that large scale systems could work in an actor style of concurrency.

I really like the idea of completely avoiding shared state. Message passing always felt like a much easier way to think about large scale systems. I can think about a single actor and the messages it sends and receives in isolation, without thinking about any other part of the system. A user types on the keyboard, and a keyboard actor sends a message to a window manager actor, which sends a message to a terminal window actor, which sends a message to an actor for a console app. An actor for a network card sends a message to the network stack actor, which sends a message to an http server actor. Each deals with its own slice of functionality, and we can reason about and test each actor in isolation. I started with the idea of “everything is an actor”, and followed that to see where it led. Ultimately, it led to a system with a powerful threadless concurrency model without locks, strong data partitioning, and the ability to hot swap any module without losing state. Before we can talk about how all of that follows from the use of the actor model, we should first talk a bit about how the actor model is used in this OS.

I won’t throw too much code at you, but I think it’s useful to start with a concrete example. In DbgOS, modules are ELF binaries with metadata describing the data types and actors in the module. The type metadata gives us a serialization format so every described type can be serialized and deserialized and can also be migrated to newer versions of the type using metadata (more on that later, because it gets us some very nice properties). These types have IDs, and get used as part of the definitions for actors. An actor is just a name, the Args type it uses for creation, the Msg type it uses for messages, and the type it uses for state. Luckily, none of the metadata needs to be written by hand because Rust has a great macro system for metaprogramming. All of the metadata is generated by a single module! macro.

use module_sdk::{Actor, Cx, Schema, log};

module_sdk::module!(name: "counter", version: 1, actors: [Counter]);

The module! macro here takes the module name and version, and a set of actor definitions. Every actor has a single Msg type it accepts in its “handle” function, and we can use a sum type (rust enum) to give us the ability of handling different types of messages. The #[derive(Schema)] on both of these types is what lets the module! macro generate the type metadata for the module.

#[derive(Schema)]
struct Counter {
    count: u64,
}

#[derive(Schema)]
enum Msg {
    Tick,
    Reset,
}

When an actor is instantiated, it has an init function that gets called. After that, all execution comes from handling messages. The Cx<> type is the main way to interact with the rest of the system. It provides a way of finding and sending messages to other actors, creating new actor instances, and a few primitives like setting a timer.

impl Actor for Counter {
    const NAME: &'static str = "Counter";
    type Args = ();
    type Msg = Msg;

    fn init((): (), cx: &mut Cx<Self>) -> Self {
        cx.set_timer(TICK, PERIOD_MS, Msg::Tick);
        Counter { count: 0 }
    }

    fn handle(&mut self, msg: Msg, cx: &mut Cx<Self>) {
        match msg {
            Msg::Tick => {
                self.count += 1;
                log!("counter: {}", self.count);
                cx.set_timer(TICK, PERIOD_MS, Msg::Tick);
            }
            Msg::Reset => self.count = 0,
        }
    }
}

There’s one last piece that makes this message communication a bit more useful. We need a way to send a request to another actor, and provide it a way to send back a response that can be connected to the original request. For that, we have a “reply slot”, represented as a ReplyTo<R> in the code for actors. That gives us the primitives we need to build a state machine for requests. While an explicit state machine might be cumbersome, we can use this to execute a Rust future with the response, letting us write async/await style code where the compiler builds the state machine for us. Something like this becomes possible:

#[derive(Schema)]
enum Msg {
    Counted(Result<u64, String>),
}

impl Actor for Fetcher {
    // ...
    fn init((): (), cx: &mut Cx<Self>) -> Self {
        cx.task(count_lines(URL.to_string()), Msg::Counted); // When the task is done, the result comes back as Msg::Counted
        // ...
    }
}

async fn count_lines(url: String) -> Result<u64, String> {
    let mut error = String::new();
    for attempt in 0..TRIES {
        if attempt > 0 {
            sleep(RETRY_MS).await;
        }
        match fetch_lines(&url).await {
            Ok(lines) => return Ok(lines),
            Err(e) => error = e,
        }
    }
    Err(error)
}

Beyond these definitions, we have a few more rules enforced by the OS:

  1. No writable segments. The loader enforces this.
  2. No blocking. None of the kernel or sdk functions provided will ever block. All messages are sent without blocking. There’s no way to directly wait for a response.
  3. A single actor instance will never be handling more than one message at a time. We never have simultaneous execution of code with access to the same writable data.
  4. A single handler execution has a limited time window and must run to completion in a small time window. The kernel enforces this by killing any instance that exceeds the limit.

A few things fall out of this:

No preemption

A handler always runs to completion in a bounded amount of time, so we can just wait for it to finish. We never need to save/restore an execution context. That means any CPU-intensive work has to be manually structured as async code that can be paused and resumed, essentially via cooperative multitasking. Not ideal, but realistically the places this is needed are small. So far in the OS the main places this has been needed are processing large files - decompression, image loading, and checksums. Fortunately, processing large chunks of memory like this are essentially the easiest things to break into chunks.

I’ll note that technically we do have a form of preemption to handle interrupts, but these have small handlers in the kernel that always return directly to the code that was interrupted, and never execute code for another instance.

No re-entrancy

Every handler runs to completion. Tasks execute in isolated contexts that don’t have access to the instance state. They can only send messages, and will send one back to their parent instance on completion. And since there’s no such thing as a “paused” execution context for a handler, any kind of re-entrancy is eliminated by construction.

No sharing of writable memory

This is enforced by a combination of the OS and compiler. As long as you don’t write unsafe rust code, it’s simply not possible for two instances to be operating on the same writable memory at once.

No locking primitives

As a follow up from the previous point: If we have no shared writable memory, there’s no need for a locking mechanism. As a result, they simply don’t exist for modules to use.

Hopefully I’ve convinced you that this model has some really nice properties. But is it actually worth the effort of avoiding threads? To answer that, let’s take a small detour and talk about how threads work.

We usually think of threads as “a way to run two pieces of code at once”, and that’s true but threads are not the only way to run two pieces of code at once. Another way to look at it is that threads are “a way to suspend a piece of code running sequentially”. The ability to suspend a piece of code is what lets us run more threads than we have processors. We give each thread a slice of time and schedule them to share the CPUs, interrupting threads that run for too long (or are waiting on another operation), suspending them so we can schedule something else.

And because we can suspend a piece of code often steers designs towards suspending execution any time code needs to wait for anything. Waiting for a TCP packet? Suspend the thread. Waiting for a subprocess to exit? Suspend the thread. Running a UI and waiting for an event from the GUI subsystem? Believe it or not, suspend the thread. While writing this post I went to check how many threads were running on my Windows desktop, and it was over 10,000 threads! Checking on my Linux server and it has 8500 threads running. Suspending a thread means saving a register context, stack pages, and any bookkeeping the OS needs for tracking the thread. An idle thread will take something like 30-70KB even while doing nothing, so this adds up. So a conservative estimate of 10,000 threads at 50KB is already 500MB. Who can afford that much memory with RAM prices these days?

It’s not a purely academic issue. In 1999 Dan Kegel coined the term C10K to describe the problem of optimizing for 10,000 simultaneous connections. The design pattern that was often used was having one thread per active connection. With this pattern, a huge chunk of resources were spent on thread management rather than the actual I/O itself. This sort of problem is the reason modern systems use mechanisms like epoll, allowing a single thread (or a small number of threads) to manage I/O for 10,000 or more connections.

The overhead of a thread is also much of the motivation for user-space concurrency. Green threads (widely used in the go language) address the issue by making threads lighter weight threads. Switches between threads are cheap, and the overhead of a suspended green thread could be as low as 2KB. It’s a pretty effective solution, and offers a programming model that feels sequential and fairly easy to understand. Other languages address the issue by using stackless coroutines for I/O (like Rust async/await), which potentially can be slightly more efficient than green threads, but this sort of model has been criticized as having a more complex programming model.

How does our threadless actor system compare here? From a memory perspective, it compares very favorably. An idle actor instance has no stack, and no register context to save. We need some kernel structures as bookkeeping for instances, but since this concept replaces both threads and processes, we don’t need bookkeeping for either of those. The major downside is the fact that we’ve essentially re-invented cooperative multitasking, and any cpu-intensive work has to be restructured so that it can yield and save its state manually, rather than automatically. This is sometimes called “manual stack management” or “stack ripping”. The cost of this sort of coding isn’t too bad with access to closures, and in particular this system uses Rust futures which simplifies the structure a fair bit. I would also argue that this cost is significantly reduced because much of that structure can be done automatically by an LLM. So yes, maybe it’s slightly more work to write code in this style, but if you don’t have to write it by hand, does it matter?

That said, the real reason I went down this road was not memory benefits, but something else: the ability to hot-swap code at any time without losing state.

Code hot-swap is not a new idea. Erlang is the classic example, and would load a new version of a module while an old version was still active, and it provided mechanisms to convert any state as a migration. Visual Studio has an “Edit and Continue”/“Hot Reload” mechanism that works for both native and managed code, letting devs edit a function, recompile, and reload the new code without restarting the process. Both Windows and Linux support kernel hotpatching, allowing security updates to be applied without a reboot.

We’ve got three main things to worry about when designing a hot swap system.

First: what’s the granularity of our swaps? The “edit and continue” system in VS can swap out functions or chunks of code. Erlang swaps out entire modules.

Second: What’s a safe time to swap code? For a kernel hot-patch of a single function, the new function can be loaded and then an atomic write to the start of a function can redirect new callers. For larger granularity, the system needs a way to quiesce to a safe point so that code isn’t swapped out from underneath anyone, or load both versions at once and have a gradual transition.

Finally: The system needs to either prevent data layout from changing, or offer a way of migrating data structure. The “edit and continue” approach can’t always apply a swap if data layout changes. Erlang provides a mechanism for explicit migrations.

In DbgOS, the granularity of a swap is a module, which is a set of actors. That leads directly to the strategy for finding a safe time for a code swap. Any instance of actor from the affected module is blocked from handling new messages, and the OS just waits for currently running handlers in those instances to finish. The system enforces a bounded time for a handler to complete, and nothing in the handlers is allowed to block. So we get to that safe point in a bounded amount of time without blocking anything else in the system. We can’t deadlock, because there are no locks, and the strong data partitions means that as soon as the affected actors aren’t executing code, any of the data for those instances will be static. That leads to the final system, which is migration of data. Because every piece of data that persists out of a handler uses #[derive(Schema)], the OS has enough metadata that any data layout changes can be applied, and can use metadata about the nesting of structures to traverse an entire tree and apply migrations hierarchically.

Yes, it works! I can make a change to the UI actor (responsible for rendering widgets) and every app in the system will use the new version without restarting. I can change out a graphics driver, storage driver, or an application all without a reboot.

The notes app in DbgOS before a hot swap

The notes app in DbgOS before a hot swap

The notes app in DbgOS after a hot swap

The notes app in DbgOS after a hot swap

It’s particularly useful in the context of using an LLM to write code. I give the coding agent the ability to push new modules to the physical machine, and it has the ability to quickly iterate without losing any of the state. If the app is in a particular state that shows a bug, I can test a fix without losing that state.

After adopting this model for my OS, lots of ideas have been going through my head of what I can do with it. Suspending/restoring the state of an application becomes fairly easy. Migrating an app to another machine entirely seems possible. Extending the message passing mechanism across multiple machines for distributed applications seems plausible too.

The most valuable part of this project for me is in re-evaluating assumptions I had about how things can work outside of what we expect from a modern operating system. No individual idea in this article is novel in itself, but combining these ideas and working through the problems (and opportunities) of doing something different helps me see other problems with a wider perspective. Should every OS get rid of threads? Definitely not. But maybe there are some cases where we can apply the ideas we learn from trying something different. So go build your own OS, but make your own weird choices and see where it leads. I’m sure you’ll learn something new. If you do, let me know what you learn. You can find me on Bluesky or LinkedIn these days.

  1. Interrupts always return to the code they interrupted, without swapping in another actor or task. The exception to this is the watchdog that fires to terminate code running more than its allowed time slice. Since we never have to save the state "for later", there's no need to save a stack or register context.
  2. Actually, the first time I checked it was over 62,000 threads. Closing firefox and VS code brought it down to 6400. Opening both again and I'm back to 13,500 threads (mostly from Firefox), so I think an estimate of 10,000 is pretty fair.
  3. I've heard more recent versions of Edit and Continue have some clever tricks that can apply changes with fields added to classes in C#, but native code changes are a bit more limited.
  4. I'll note that some layout changes need explicit annotation. Removed, renamed, and added fields need to be annotated, and a changed structure may need a hand written migration. We can verify that the metadata exists and is compatible with a running version before swapping it in.
联系我们 contact @ memedata.com