JanetDocsPlaygroundI'm feeling luckyGitHub sign in

ev/spawn-thread



    macro
    boot.janet on line 3572, column 3

    (ev/spawn-thread & body)

    Run some code in a new thread. Like `ev/do-thread`, but returns nil 
    immediately.


1 exampleSign in to add an example
Loading...
# Run this in a file.
# Notice how each thread gets its own copy of the environment,
# including the global 'counter' variable.

(var counter 0)
(defn start-thread [name sleep]
  (def chan (ev/thread-chan))
  (ev/spawn-thread
    (repeat 10
      (ev/sleep sleep)
      (++ counter)
      (print name " counter is " counter))
    (print name " has finished")
    (ev/give chan "done"))
  chan)

# Spawn two threads that increment counter
(def chan-a (start-thread "Slow thread" 0.8))
(def chan-b (start-thread "Fast thread" 0.45))

# Wait for both threads to finish
(ev/take chan-a)
(ev/take chan-b)
(print "Global counter is still " counter)
fuxoftPlayground