I\'ve read a lot about how great Clojure is when it comes to concurrency, but none of the tutorials I\'ve read actually explain how to create a thread. Do you just do (.start (T
Programming Clojure doesn't address that question until page 167: "Use Agents for Asynchronous Updates".
Before you go starting threads, please note that Clojure will multitask on its own, given half a chance. I've written programs blithely ignorant of concurrency and found that when conditions are right, they occupy more than one CPU. I know that's not a very rigorous definition: I haven't explored this in depth yet.
But for those occasions when you really do need an explicit separate activity, one of Clojure's answers is apparently the agent.
(agent initial-state)
will create one. It's not like a Java Thread in terms of being a code block waiting to be executed. Instead, it's an activity waiting to be given work to do. You do this via
(send agent update-fn & args)
The example does
(def counter (agent 0))
counter
is your name and handle for the agent; the agent's state is the number 0.
Having set that up, you can send work to the agent:
(send counter inc)
will tell it to apply the given function to its state.
You can later pull the state out of the agent by dereferencing it:
@counter
will give you the current value of the number that started out at 0.
Function await
will let you do something like a join
on the agent's activity, should it be a long one:
(await & agents)
will wait until they're all done; there's also another version that takes a timeout.