If you peruse my last post, you cognize that I’m making my own OS, DbgOS. If you haven’t peruse that, the abbreviated type is that I’m making an OS from scratch in Rust so I can try distinct ideas in OS scheme and study new things by making different choices. This period I desire to conversation concerning the decisions about how the OS deals alongside concurrency. Long the bane of our existence, concurrency bugs are difficult to find, difficult to analyze, and extremely uncomplicated to make. Over the former 50+ years, we’ve invented many schemes to entirely evade this category of bugs, and many of them revolve about eliminating shared state. One specified example is the actor model, which originated in a 1973 paper by Carl Hewitt, Peter Bishop, and Richard Steiger. The component of concurrency current is (unsurprisingly) an “actor”. Each performer operates independently, has its own mailbox, and can dispatch messages to another actors, but cannot portion data any another way. The performer example is frequently connected alongside Erlang, although the Erlang designers weren’t explicitly example on this document as a reference. But it did display that ample measure systems could activity in an performer manner of concurrency.
I really akin the idea of entirely avoiding shared state. Message passing continually felt akin a much easier way to think concerning ample measure systems. I can think concerning a sole performer and the messages it sends and receives in isolation, without thinking concerning any another part of the system. A person types on the keyboard, and a keyboard performer sends a communication to a opening director actor, which sends a communication to a terminal opening actor, which sends a communication to an performer for a console app. An performer for a network cardstock sends a communication to the network stack actor, which sends a communication to an http server actor. Each deals alongside its own piece of functionality, and we can logic concerning and test all performer in isolation. I started alongside the idea of “everything is an actor”, and followed that to see anywhere it led. Ultimately, it led to a scheme alongside a powerful threadless concurrency example without locks, powerful data partitioning, and the capability to hot toggle any component without losing state. Before we can conversation concerning how all of that follows from the use of the performer model, we should archetypal conversation a bit concerning how the performer example is used in this OS.
I won’t throw too much code at you, but I think it’s helpful to commencement alongside a tangible example. In DbgOS, modules are ELF binaries alongside metadata describing the data types and actors in the module. The category metadata gives us a serialization format so all described category can be serialized and deserialized and can additionally be migrated to newer versions of the category using metadata (more on that later, since it gets us several extremely nice properties). These types have IDs, and get used as part of the definitions for actors. An performer is fair a name, the Args category it uses for creation, the Msg category it uses for messages, and the category it uses for state. Luckily, none of the metadata needs to be written by hand since Rust has a awesome macro scheme for metaprogramming. All of the metadata is generated by a sole module! macro.
use module_sdk::{Actor, Cx, Schema, log}; module_sdk::module!(name: "counter", version: 1, actors: [Counter]);
The module! macro current takes the component name and version, and a set of performer definitions. Every performer has a sole Msg category it accepts in its “handle” function, and we can use a sum category (rust enum) to provision us the capability of handling distinct types of messages. The #[derive(Schema)] on the two of these types is what lets the module! macro create the category metadata for the module.
#[derive(Schema)] struct Counter { count: u64, } #[derive(Schema)] enum Msg { Tick, Reset, }
When an performer is instantiated, it has an init function that gets called. After that, all implementation comes from handling messages. The Cx<> category is the chief way to engage alongside the remainder of the system. It provides a way of finding and sending messages to another actors, creating new performer instances, and a few primitives akin environment 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 final part that makes this communication communication a bit additional useful. We need a way to dispatch a petition to another actor, and provision it a way to dispatch rear a reply that can be connected to the first 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 province device for requests. While an definitive province device power be cumbersome, we can use this to execute a Rust forthcoming alongside the response, letting us compose async/await manner code anywhere the compiler builds the province device for us. Something akin 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 project is done, the outcome comes rear 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 additional rules enforced by the OS:
- No writable segments. The loader enforces this.
- No blocking. None of the kernel or sdk functions provided volition always block. All messages are sent without blocking. There’s no way to immediately delay for a response.
- A sole performer case volition never be handling additional than one communication at a time. We never have simultaneous implementation of code alongside admission to the identical writable data.
- A sole handler implementation has a constricted period opening and must run to completion in a small period window. The kernel enforces this by slaying any case that exceeds the limit.
A few things autumn out of this:
No preemption
A handler continually runs to completion in a bounded amount of time, so we can fair delay for it to finish. We never need to save/restore an implementation context. That method any CPU-intensive activity have to be manually organized as async code that can be paused and resumed, basically via cooperative multitasking. Not ideal, but realistically the places this is needed are small. So far in the OS the chief places this has been needed are handling ample records - decompression, depiction loading, and checksums. Fortunately, handling ample chunks of recollection akin this are basically the easiest things to interrupt into chunks.
I’ll note that technically we do have a form of preemption to grip interrupts, but these have small handlers in the kernel that always come back 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 secluded contexts that don’t have admission to the case state. They can lone dispatch messages, and volition dispatch one rear to their genitor case on completion. And since there’s no specified item as a “paused” implementation environment for a handler, any benevolent of re-entrancy is eliminated by construction.
No sharing of writable memory
This is enforced by a blend of the OS and compiler. As lengthy as you don’t compose unsafe rust code, it’s merely not imaginable for two instances to be functioning on the identical writable recollection at once.
No locking primitives
As a prosecute up from the former point: If we have no shared writable memory, there’s no need for a locking mechanism. As a result, they merely don’t be for modules to use.
Hopefully I’ve convinced you that this example has several really nice properties. But is it really value the attempt of avoiding threads? To answer that, let’s obtain a small detour and conversation concerning how threads work.
We normally think of threads as “a way to run two pieces of code at once”, and that’s true but threads are not the lone way to run two pieces of code at once. Another way to appearance at it is that threads are “a way to suspend a part of code operating sequentially”. The capability to suspend a part of code is what lets us run additional threads than we have processors. We provision all thread a piece of period and agenda them to portion the CPUs, interrupting threads that run for too lengthy (or are waiting on another operation), suspending them so we can agenda item else.
And since we can suspend a part of code frequently steers designs towards suspending implementation any period code needs to delay 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 penning this article I went to inspect how many threads were operating 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 method preservation a enroll context, stack pages, and any bookkeeping the OS needs for tracking the thread. An idle thread volition obtain item akin 30-70KB equal during doing nothing, so this adds up. So a traditional evaluation of 10,000 threads at 50KB is already 500MB. Who can oversee that much recollection alongside RAM prices these days?
It’s not a purely scholarly issue. In 1999 Dan Kegel coined the term C10K to depict the issue of optimizing for 10,000 simultaneous connections. The scheme form that was frequently used was having one thread per energetic connection. With this pattern, a huge chunk of resources were spent on thread administration fairly than the genuine I/O itself. This kind of issue is the logic contemporary systems use mechanisms akin epoll, allowing a sole thread (or a small figure of threads) to oversee I/O for 10,000 or additional connections.
The overhead of a thread is additionally much of the motivation for user-space concurrency. Green threads (widely used in the go language) location the matter by making threads lighter importance threads. Switches between threads are cheap, and the overhead of a suspended green thread could be as low as 2KB. It’s a beautiful productive solution, and offers a programming example that feels sequential and fairly uncomplicated to understand. Other languages location the matter by using stackless coroutines for I/O (like Rust async/await), which possibly can be slightly additional productive than green threads, but this kind of example has been criticized as having a additional complex programming model.
How does our threadless performer scheme difference here? From a recollection perspective, it compares extremely favorably. An idle performer case has no stack, and no enroll environment to save. We need several kernel structures as bookkeeping for instances, but since this idea replaces the two threads and processes, we don’t need bookkeeping for either of those. The important downside is the fact that we’ve basically re-invented cooperative multitasking, and any cpu-intensive activity have to be restructured so that it can output and preserve its province manually, fairly than automatically. This is sometimes called “manual stack management” or “stack ripping”. The disbursal of this kind of coding isn’t too bad alongside admission to closures, and in particular this scheme uses Rust futures which simplifies the construction a fair bit. I would additionally contend that this disbursal is considerably reduced since much of that construction can be done automatically by an LLM. So yes, perchance it’s slightly additional activity to compose code in this style, but if you don’t have to compose it by hand, does it matter?
That said, the genuine logic I went downward this highway was not recollection benefits, but item else: the capability to hot-swap code at any period without losing state.
Code hot-swap is not a new idea. Erlang is the traditional example, and would burden a new type of a component during an old type was motionless active, and it provided mechanisms to change any province as a migration. Visual Studio has an “Edit and Continue”/“Hot Reload” scheme that plant for the two native and managed code, letting devs edit a function, recompile, and reload the new code without restarting the process. Both Windows and Linux assistance kernel hotpatching, allowing safety updates to be applied without a reboot.
We’ve got three chief things to concern concerning whenever designing a hot toggle system.
First: what’s the granularity of our swaps? The “edit and continue” scheme in VS can toggle out functions or chunks of code. Erlang swaps out complete modules.
Second: What’s a harmless period to toggle code? For a kernel hot-patch of a sole function, the new function can be loaded and afterward an nuclear compose to the commencement of a function can redirect new callers. For larger granularity, the scheme needs a way to quiesce to a harmless item so that code isn’t exchanged out from underneath anyone, or burden the two versions at formerly and have a gradual transition.
Finally: The scheme needs to either forestall data layout from changing, or recommendation a way of migrating data structure. The “edit and continue” method can’t continually use a toggle if data layout changes. Erlang provides a scheme for definitive migrations.
In DbgOS, the granularity of a toggle is a module, which is a set of actors. That leads immediately to the scheme for finding a harmless period for a code swap. Any case of performer from the affected component is blocked from handling new messages, and the OS fair waits for currently operating handlers in those instances to finish. The scheme enforces a bounded period for a handler to complete, and nothing in the handlers is allowed to block. So we get to that harmless item in a bounded amount of period without blocking item alternatively in the system. We can’t deadlock, since there are no locks, and the powerful data partitions method that as shortly as the affected actors aren’t executing code, any of the data for those instances volition be static. That leads to the final system, which is immigration of data. Because all part of data that persists out of a handler uses #[derive(Schema)], the OS has adequate metadata that any data layout changes can be applied, and can use metadata concerning the nesting of structures to traverse an complete tree and use migrations hierarchically.
Yes, it works! I can create a alter to the UI performer (responsible for rendering widgets) and all app in the scheme volition use the new type without restarting. I can alter out a graphics driver, retention driver, or an use all without a reboot.

The notes app in DbgOS before a hot swap

The notes app in DbgOS following a hot swap
It’s particularly helpful in the environment of using an LLM to compose code. I provision the coding delegate the capability to shove new modules to the bodily machine, and it has the capability to quickly iterate without losing any of the state. If the app is in a particular province that shows a bug, I can test a fix without losing that state.
After adopting this example for my OS, many of ideas have been going through my caput of what I can do alongside it. Suspending/restoring the province of an use becomes fairly easy. Migrating an app to another device entirely seems possible. Extending the communication passing scheme throughout multiple machines for distributed applications seems plausible too.
The most precious part of this project for me is in re-evaluating assumptions I had concerning how things can activity exterior of what we anticipate from a contemporary functioning system. No idiosyncratic idea in this part is novel in itself, but combining these ideas and operating through the problems (and opportunities) of doing item distinct helps me see another problems alongside a wider perspective. Should all OS get rid of threads? Definitely not. But perchance there are several cases anywhere we can use the ideas we study from trying item different. So go build your own OS, but create your own weird choices and see anywhere it leads. I’m certain you’ll study item new. If you do, let me cognize what you learn. You can find me on Bluesky or LinkedIn these days.