Skip to content

Commit f16cae7

Browse files
committed
Merge pull request #439 from mpenet/feature/csp-timeout
add csp/timeout channel
2 parents ed99e53 + 7c09904 commit f16cae7

File tree

3 files changed

+36
-0
lines changed

3 files changed

+36
-0
lines changed

pixie/channels.pxi

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
(ns pixie.channels
22
(:require [pixie.stacklets :as st]
3+
[pixie.uv :as uv]
4+
[pixie.ffi :as ffi]
35
[pixie.buffers :as b]))
46

57
(defprotocol ICancelable
@@ -143,6 +145,24 @@
143145
false
144146
0)))))
145147

148+
(defn timeout
149+
"Returns a channel that will close after given delay in ms"
150+
[ms]
151+
(let [ch (chan)
152+
timer (uv/uv_timer_t)
153+
cb (atom nil)]
154+
(reset! cb (ffi/ffi-prep-callback uv/uv_timer_cb
155+
(fn [handle]
156+
(try
157+
(-close! ch)
158+
(uv/uv_timer_stop timer)
159+
(-dispose! @cb)
160+
(catch ex
161+
(println ex))))))
162+
(uv/uv_timer_init (uv/uv_default_loop) timer)
163+
(uv/uv_timer_start timer @cb ms 0)
164+
ch))
165+
146166
(deftype AltHandler [atm f]
147167
ICancelable
148168
(-canceled? [this]

pixie/csp.pxi

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
[pixie.channels :as chans]))
55

66
(def chan chans/chan)
7+
(def timeout chans/timeout)
78

89
(defn close!
910
"Closes the channel, future writes will be rejected, future reads will

tests/pixie/tests/test-csp.pxi

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,3 +31,18 @@
3131
(assert= (alts! [c] :default 42) [:default 42])
3232
(>! c 1)
3333
(assert= (alts! [c] :default 42) [c 1])))
34+
35+
(deftest test-timeout-channel
36+
(let [ts [(timeout 300)
37+
(timeout 200)
38+
(timeout 100)]]
39+
(-> (go
40+
(loop [ts (set ts)
41+
res []]
42+
(if (empty? ts)
43+
res
44+
(let [[p _] (alts! ts)]
45+
(recur (set (remove #{p} ts))
46+
(conj res p))))))
47+
<!
48+
(assert= (reverse ts)))))

0 commit comments

Comments
 (0)