Last updated: 2026-11-15

U
Undergraduate level
APL
Applied / Methodological โ€” Knowledge with a 5โ€“10 year half-life โ€” stable practice

Worlds, Fibers and Threads in PatLang 2.0

For new readers

PatLang has three ways to run code alongside other code. A fiber is a function that can pause and be resumed later, on the same thread. A thread runs a closure truly in parallel. A world, new in v2, is a separate copy of a program's state, its objects, classes, handlers, rules and files, so that code run in it can neither see nor disturb the program that called it, and a crash inside it ends only that call. This page covers all three and how they combine.crash isolation is a key safety feature

The rules are sections 1.8 and 1.15 of the values-and-memory specification. Fibers and threads existed in v1 and are described with more examples in Fibers and Real OS threads; this page gives the v2 rules and the parts that are new.

Fibers FoundationalKnowledge that endures for decades โ€” core principles

fiber_new(name) makes a fiber of a named function. fiber_resume(id, v) runs it until it yields or returns, handing it v, and gives what it yielded or returned; the first resume's value is the function's argument. fiber_yield(v) goes back to whoever resumed the fiber, and gives what the next resume hands it. fiber_alive(id) is true until the function has returned.

make a function called counter takes start returns r
  let n = start
  while n < start + 3 do
    let got = fiber_yield(n)
    let n = n + 1
  end
  return "finished"
end
let f = fiber_new("counter")
print(fiber_resume(f, 10))
print(fiber_resume(f, "a"))
print(fiber_resume(f, "b"))
print(fiber_resume(f, "c"))
print(fiber_alive(f))
10
11
12
finished
false

Resuming a finished fiber, and yielding when no fiber is running, stop the program. A fiber that never finishes keeps its stack and whatever its frames hold, since its id can still resume it; that is what a fiber is for.the stack lives until the fiber does

Budgeted blocks Applied / MethodologicalKnowledge with a 5โ€“10 year half-life โ€” stable practice

budgeted(ms, handle) { body } runs the body on a fiber until ms milliseconds have passed. It checks the clock at each back-edge of a loop written in the body, and yields early if the next iteration, judged by the recent ones, would pass the deadline. It gives ["done", value] or ["paused", handle], and passing the handle back in continues the body where it stopped. The body captures what it reads, as a closure does.

let r = budgeted(1000, unit) {
  let i = 0
  while i < 1000 do
    let i = i + 1
  end
  i
}
print(r)
[done, 1000]

Threads FoundationalKnowledge that endures for decades โ€” core principles

thread_spawn(closure, args...) calls the closure with the arguments after it on a thread of its own, and the number of arguments is checked as any closure call's is. In v1 a thread passed its closure no arguments at all. thread_poll(id) says, without waiting, whether the thread has finished. thread_result(id) waits for it and gives what it returned, once: taking the result gives back everything the thread held, and a second call stops the program.

let square = |x| { return x * x }
let t = thread_spawn(square, 12)
print(thread_result(t))
144

Any number of threads may run the same function at once, including the first time it is ever called, and each gives what one thread alone would. That sentence is in the specification because the v2 interpreter broke it at first: threads calling a function for the first time raced on the interpreter's caches, and 19 of 40 cold runs of the language suite failed in different ways. Each call site's cached target is now a cell written once.

The runtime keeps per-thread state in each thread's context: its free lists, its list of running event handlers, the word a system call writes a count into, and a buffer for formatting numbers. That last pair was once shared by every thread, and the native compiler running eight workers failed at random on 4 of 21 compiles because one thread read another's byte count.cf. blocks: isolating state per thread

Worlds FoundationalKnowledge that endures for decades โ€” core principles

A world is where a program's state lives: its named objects, its classes, the handlers registered for events, the functions reached by name, its logic stores, actions and goals, the contract facts recorded, and its virtual files. A program starts in a world of its own, and can make more.

  • world_new() gives a new world, an int, holding what a program that has just started holds: the built-in classes and nothing else, apart from the functions reached by name of the world that made it.
  • world_call(w, f) calls the closure f, which takes no arguments, in world w, on a fiber of its own, and gives ["done", value]. What f adds, declares, registers or writes goes into w, and none of it into the caller's world.
  • What code in another world prints goes to that world, not to standard output; world_output(w) gives everything printed in w so far.
  • world_free(w) gives back everything w holds. Freeing the world that code is running in stops the program.
rule colour(sky, blue).
let w = world_new()
print("before")
let r = world_call(w, || {
  print("inside the world")
  rule colour(grass, green).
  return solve("colour", ["T", "C"])
})
print(r)
print(solve("colour", ["T", "C"]))
print(world_call(w, || { return solve("colour", ["T", "C"]) }))
print(world_output(w))
world_free(w)
before
[done, [[grass, green]]]
[[sky, blue]]
[done, [[grass, green]]]
inside the world

The world never saw the program's sky fact, the program never saw the world's grass fact, and a second call into the same world found what the first had added. The line printed inside the world appears only when the program prints world_output(w).

A value f returns is an ordinary value in the caller's world, with one exception: an object of a class the world declared is taken out as plain data, its fields' values, and never as the object, since its class belongs to the world.

A stop ends the call, not the program

When code running in world_call stops, by a failed contract, exit_with, a call to a name nothing declares or any other stop, the stop ends the call. world_call gives ["stopped", code], with the exit code the program would have stopped with, and its caller goes on. What the stop said is in the world's output.

make a function called halve takes n returns r
  require n % 2 == 0
  return n / 2
end
let bad = world_new()
print(world_call(bad, || {
  print("about to fail")
  return halve(3)
}))
print(world_output(bad))
world_free(bad)
print("the program goes on")
[stopped, 3]
about to fail
contract violation: precondition failed in halve(): n % 2 == 0

the program goes on

The frames between the stop and the call are unwound, and what they held is given back, including the frames of fibers that code in the call resumed. Before unwinding was built, a loop of stopping world calls grew from 16 MB at 200 stops to 119 MB at 2,000; it now holds at 5 MB compiled and 15 MB interpreted at both counts. Inside a compiled program explains the mechanism.

Step budgets

world_steps(w, n) gives a world a budget of n steps, and world_step() spends one step of the budget of the world the code runs in. When a step is spent with none left, the world stops with step budget of N exhausted, exit code 78. A world has no budget until it is given one, and the program's own world has none.

let loop = world_new()
world_steps(loop, 500)
print(world_call(loop, || {
  while true do
    world_step()
  end
  return 0
}))
print(world_output(loop))
world_free(loop)
[stopped, 78]
step budget of 500 exhausted

The interpreter spends a step at each call and at each jump back to an earlier instruction, so a budget bounds anything a program interpreted in a world can do, without the program having to call world_step itself. Compiled code spends none.see how compilation skips the meter

Fibers, threads and nested worlds

  • A fiber runs in the world it was made in, whoever resumes it.
  • A thread runs in the world of the code that started it. A stop on such a thread ends that thread: its frames are unwound, thread_poll gives true, thread_result gives unit, and world_call gives ["stopped", code] with the first stop's code when f returns.
  • world_call may run inside a world, so worlds nest, each with its own state.
  • A paused fiber made in a world is unwound when the world is freed.

What worlds are used for Applied / MethodologicalKnowledge with a 5โ€“10 year half-life โ€” stable practice

v1's world_run ran a program in-process by swapping every global store for an empty one and swapping them back afterwards. v2 swaps nothing: each thread's context names the world its code runs in, and the runtime looks everything up through it. Three parts of the toolchain are built on that:

  • Running source text. lib/interp_run.patlang's world backend compiles a program's text with the compiler's front end and runs it in a fresh world on the v2 interpreter, which is a library as well as a command. A run costs about 100 milliseconds. The browser playground, REPL and IDE are this backend built as WebAssembly.
  • Isolates. Each isolate's turn runs in a world, so isolates exchange messages through mailboxes and share no state.
  • Untrusted or unfinished code. A stop ends the call and a budget ends a runaway loop, so a host program can run code it does not trust to finish.

A call of a runtime function in a program the interpreter runs reaches the function as the interpreter has it, whatever the program registers under that name when it starts. That rule was added after a program that asked for every runtime function by name reached its own registrations, which called themselves until the stack overflowed.recursive call when the function calls itself

In a browser, each thread and each fiber runs on a Web Worker of its own over one shared memory. Starting a fiber there takes milliseconds, against microseconds natively, and so does each budgeted block, which runs on a fiber.

See also

Fibers, Real OS threads and Robots: cross-thread signalling show the older concurrency features in use. The live playground and the REPL run code in worlds in the browser. Journey Chapter 16 tells how closures, threads, fibers and worlds first went native in v1.

Graduate Attributes

Modelled on this page

  • Researcher: Specific failure counts from test suites are cited to justify changes to the interpreter's caching mechanism.
  • Digitally Fluent: Technical distinctions between fibers, threads and worlds are defined with precise operational semantics.
  • Reflective: Previous implementation errors regarding shared state and race conditions are described to explain current design choices.

University of Reading Graduate Attributes framework.