Problem w/ daemon threads

72 views
Skip to first unread message

Sean Devlin

unread,
Nov 12, 2009, 10:50:31 AM11/12/09
to Clojure
Hi all,
I'm trying to get a periodic daemon thread working. I've read some of
the stuff here:

http://groups.google.com/group/clojure/browse_thread/thread/4bc06d413fda157f/e953bb0c9286c5a7

With no luck. My code looks like this

(defn daemon
"Creates a new daemon thread and sets runnable to f"
[f]
(let [t (Thread. f)]
(do
(.setDaemon t true)
(.start t)
t)))

And I tried calling

user=>(daemon #(println "foo"))

I get the thread back, but it does not appear to execute. I've tried
this on OSX and XP. Does anyone know what I'm doing wrong?

Sean

David Brown

unread,
Nov 12, 2009, 11:09:59 AM11/12/09
to clo...@googlegroups.com
On Thu, Nov 12, 2009 at 07:50:31AM -0800, Sean Devlin wrote:

>(defn daemon
> "Creates a new daemon thread and sets runnable to f"
> [f]
> (let [t (Thread. f)]
> (do
> (.setDaemon t true)
> (.start t)
> t)))
>
>And I tried calling
>
>user=>(daemon #(println "foo"))
>
>I get the thread back, but it does not appear to execute. I've tried
>this on OSX and XP. Does anyone know what I'm doing wrong?

I tried this on Linux, and prints "foo" once, which is what I would
expect.

If you want it to be period, though, you'll need to use something like
Executors/newSingleThreadScheduledExecutor to create a scheduler for
it.

I tried writing a periodic scheduler using agents (and a ref to manage
state). Turns out that getting shutdown working robustly is actually
fairly tricky. I recommend just using the scheduler available in
Java.

David

Sean Devlin

unread,
Nov 12, 2009, 11:21:12 AM11/12/09
to Clojure
Blargh!!! I've committed a good old-fashioned PEBCAK.

I should have been more specific. I executed this in SLIME/OSX and
enclojure/XP. The problem was that the output wasn't going to *out*
like I'd expect.

I tried a different example, and everything is cool.

user=>(def my-agent (agent 0))

user=>(daemon #(send my-agent inc))

user=>@my-agent
1

D'oh!
Sean
Reply all
Reply to author
Forward
0 new messages