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:
-fn
(defn some
[]yield 1)
(yield 2)
(3)
def f (fiber/new some-fn))
(type f) # -> :fiber
(/status f) # -> :new
(fiber# -> 1
(resume f) /status f) # -> :pending
(fiber# -> 2
(resume f) # -> 3
(resume f) /status f) # -> :dead
(fiber# ERROR (resume f)
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
?
label
?
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.