An OS with no threads: The Actor Model
An OS with no threads - The Actor Model
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.
Actors, Types, and Modules
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 {
cx.set_timer(TICK, PERIOD_MS, Msg::Tick);
Counter { count: 0 }
}
fn handle(&mut self, msg: Msg, cx: &mut Cx ) {
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 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 ),
}
impl Actor for Fetcher {
// ...
fn init((): (), cx: &mut Cx ) -> 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 {
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:
- No writable segments. The loader enforces this.
- 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.
- 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.
- 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.
Pulling at Threads
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.
Swapping the Wing on a Flying Plane
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
Comments
No comments yet. Start the discussion.