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>
- The compiler compiles each
spawn { ... }body into a hidden closure function capturing any referenced outer locals by value (O(1)Arcclones). - 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 withstd::thread::spawn, and wraps theJoinHandle<Result<Value, Diagnostic>>inside aValue::Task(TaskHandle). - Calling
join(task)takes theJoinHandleout of theMutex<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)
- Before binding the socket,
run_http_servevalidates that the port is in1..=65535and that the handler (Value::FnorValue::Closure) has effective arity== 1. TcpListener::bind(("127.0.0.1", port))listens for incoming TCP streams.- For each connection,
http_servespawns a worker thread with a freshspawn_child()VM, parses the HTTP/1.1 request line,Content-Length, and body, invokes the handler, validates the response status (200..=599), strips bodies for204/304, and writes the response withConnection: close.