Janet Notes and Examples

Fibers, Threads, and the Event Loop

Fibers are Janet’s support for cooperative userland threads of execution. Some relevant functions are fiber/new, fiber/status, yield, and resume.

You make a new fiber like so:

(defn some-fn
  (yield 1)
  (yield 2)

(def f (fiber/new some-fn))
(type f)          # -> :fiber
(fiber/status f)  # -> :new
(resume f)        # -> 1
(fiber/status f)  # -> :pending
(resume f)        # -> 2
(resume f)        # -> 3
(fiber/status f)  # -> :dead
(resume f)        # ERROR

See the official docs at Janet Fiber docs.

Misc notes down here to eventually make sense of and weave into the above docs.

Note: Janet also supports full native preemptive multithreading as well. See Janet Thread docs. — wait, no, don’t use “threads” for this; use the threaded channels and ev instead.

You can get the old threads functionality with ev/do-thread and ev/spawn-thread. If a function has “thread” in it, then it’s using true threads.

Communication is done with channels (rather than a send and receive scheme).

Regular channels vs thread channels: “Threaded channels make copies of every item you put in an can send values between threads. Normal channels don’t.”

signal? Exceptions? Raising/catching? (I think error is for raising).

error vs prompt?


ev module, dyns

ev/spawn — creates a fiber and immediately schedules it on the event loop.

Note: there’s a difference between a fiber on the event loop (which has been “scheduled”) vs just any old fiber.