Internals · 06

Concurrency Implementation

How Ochre implements colorless spawn/join tasks, typed Channel<T> queues, and multi-threaded HTTP/1.1 handling inside ochre-vm.

Ochre's concurrency runtime in ochre-vm is built directly on Rust's std::thread, std::sync::mpsc, and Arc Copy-on-Write values — keeping the implementation simple, deterministic, and free of async runtime coloring.

spawn { ... } & Task<T>

  1. The compiler compiles each spawn { ... } body into a hidden closure function capturing any referenced outer locals by value (O(1) Arc clones).
  2. At runtime (Op::Spawn), the VM clones its immutable function table and globals into a lightweight child VM (spawn_child()), spawns a native OS thread with std::thread::spawn, and wraps the JoinHandle<Result<Value, Diagnostic>> inside a Value::Task(TaskHandle).
  3. Calling join(task) takes the JoinHandle out of the Mutex<Option<JoinHandle<...>>> and blocks until the thread finishes, propagating any runtime diagnostic cleanly back to the caller.

Typed Channels (Channel<T>)

A Channel<T> is backed by a thread-safe Arc<(Mutex<VecDeque<Value>>, Condvar, AtomicBool)> (or synchronized queue + closed flag):

  • send(ch, val) pushes a value onto the queue and notifies waiting receivers.
  • recv(ch) blocks until either a value is available (Some(val)) or the channel is closed and drained (None).
  • close(ch) marks the channel closed and wakes all blocked receivers so consumer loops terminate cleanly without deadlocks.

Multi-Threaded HTTP/1.1 (http_serve)

  1. Before binding the socket, run_http_serve validates that the port is in 1..=65535 and that the handler (Value::Fn or Value::Closure) has effective arity == 1.
  2. TcpListener::bind(("127.0.0.1", port)) listens for incoming TCP streams.
  3. For each connection, http_serve spawns a worker thread with a fresh spawn_child() VM, parses the HTTP/1.1 request line, Content-Length, and body, invokes the handler, validates the response status (200..=599), strips bodies for 204/304, and writes the response with Connection: close.