1
0
mirror of https://github.com/janet-lang/janet synced 2025-10-06 11:32:29 +00:00

Update threads.c to avoid a deadlock.

This commit is contained in:
Calvin Rose
2019-12-06 01:46:23 -06:00
parent dbcceefc20
commit c804ae9f7c
3 changed files with 235 additions and 161 deletions

View File

@@ -1,10 +1,11 @@
(defn worker-main
"Sends 11 messages back to parent"
[parent]
(def name (:receive parent))
(def interval (:receive parent))
(for i 0 10
(os/sleep interval)
(printf "thread %s wakeup no. %d" name i))
(:send parent (string/format "thread %s wakeup no. %d" name i)))
(:send parent name))
(defn make-worker
@@ -14,10 +15,45 @@
(:send name)
(:send interval)))
(def bob (make-worker "bob" 0.2))
(def joe (make-worker "joe" 0.3))
(def sam (make-worker "sam" 0.5))
(def bob (make-worker "bob" 0.02))
(def joe (make-worker "joe" 0.03))
(def sam (make-worker "sam" 0.05))
(:close joe)
(try (:receive joe) ([err] (print "Got expected error: " err)))
# Receive out of order
(for i 0 3
(print "worker " (thread/receive [bob sam joe]) " finished!"))
(for i 0 22
(print (thread/receive [bob sam])))
#
# Recursive Thread Tree - should pause for a bit, and then print a cool zigzag.
#
(def rng (math/rng (os/cryptorand 16)))
(defn choose [& xs]
(in xs (:int rng (length xs))))
(defn worker-tree
[parent]
(def name (:receive parent))
(def depth (:receive parent))
(if (< depth 5)
(do
(defn subtree []
(-> (thread/new)
(:send worker-tree)
(:send (string name "/" (choose "bob" "marley" "harry" "suki" "anna" "yu")))
(:send (inc depth))))
(let [l (subtree)
r (subtree)
lrep (thread/receive l)
rrep (thread/receive r)]
(:send parent [name ;lrep ;rrep])))
(do
(:send parent [name]))))
(def lines (:receive (-> (thread/new) (:send worker-tree) (:send "adam") (:send 0))))
(map print lines)