|
| 1 | +(ns pixie.stacklets |
| 2 | + (require pixie.uv :as uv)) |
| 3 | + |
| 4 | +(def stacklet-loop-h (atom nil)) |
| 5 | + |
| 6 | +(defn -spawn-thread [fn] |
| 7 | + (let [[h val] (@stacklet-loop-h [:spawn fn])] |
| 8 | + (reset! stacklet-loop-h h) |
| 9 | + (println h val) |
| 10 | + val)) |
| 11 | + |
| 12 | +(defn enqueue [q itm] |
| 13 | + ; TODO: Rewrite this crappy impl |
| 14 | + (vec (conj (seq q) itm))) |
| 15 | + |
| 16 | +(defn dequeue [q] |
| 17 | + [(ith q -1) |
| 18 | + (pop q)]) |
| 19 | + |
| 20 | + |
| 21 | +(defn yield-control [] |
| 22 | + (let [[h] (@stacklet-loop-h [:yield nil])] |
| 23 | + (reset! stacklet-loop-h h) |
| 24 | + nil)) |
| 25 | + |
| 26 | + |
| 27 | +(defmacro spawn [& body] |
| 28 | + `(let [f (fn [h# _] |
| 29 | + (reset! stacklet-loop-h h#) |
| 30 | + (try |
| 31 | + (println "spawn" h#) |
| 32 | + ;(reset! stacklet-loop-h h#) |
| 33 | + (let [result# (do ~@body)] |
| 34 | + (println "returning " result#) |
| 35 | + (@stacklet-loop-h [:spawn-end result#])) |
| 36 | + (catch e (println e)))) |
| 37 | + [h# val#] (@stacklet-loop-h [:spawn f])] |
| 38 | + (reset! stacklet-loop-h h#) |
| 39 | + val#)) |
| 40 | + |
| 41 | +(defn -with-stacklets [fn] |
| 42 | + (let [[h [op arg]] ((new-stacklet fn) nil)] |
| 43 | + (println h op arg) |
| 44 | + (loop [op op |
| 45 | + arg arg |
| 46 | + this_h h |
| 47 | + tasks []] |
| 48 | + (println "in loop" op arg this_h tasks) |
| 49 | + (cond |
| 50 | + (= op :spawn) (let [wh (new-stacklet arg) |
| 51 | + [h [op arg]] (this_h nil)] |
| 52 | + (recur op arg h (enqueue tasks wh))) |
| 53 | + (= op :yield) (let [tasks (enqueue tasks this_h) |
| 54 | + [task tasks] (dequeue tasks) |
| 55 | + [h [op arg]] (task nil)] |
| 56 | + (recur op arg h tasks)) |
| 57 | + (= op :spawn-end) (if (empty? tasks) |
| 58 | + arg |
| 59 | + (let [[task tasks] (dequeue tasks) |
| 60 | + [h [op arg]] (task nil)] |
| 61 | + (recur op arg h tasks))) |
| 62 | + :else (assert false (str "Unkown command " op " " arg)))))) |
| 63 | + |
| 64 | + |
| 65 | +(defmacro with-stacklets [& body] |
| 66 | + `(-with-stacklets |
| 67 | + (fn [h# _] |
| 68 | + (try |
| 69 | + (println h# _) |
| 70 | + (reset! stacklet-loop-h h#) |
| 71 | + (let [result# (do ~@body)] |
| 72 | + (@stacklet-loop-h [:spawn-end result#])) |
| 73 | + (catch e |
| 74 | + (println e)))))) |
| 75 | + |
| 76 | +(with-stacklets (spawn (dotimes [x 10] |
| 77 | + (yield-control) |
| 78 | + (println x))) |
| 79 | + (spawn (dotimes [x 10] |
| 80 | + (yield-control) |
| 81 | + (println x)))(yield-control)) |
0 commit comments