How does one start a thread in Clojure?

后端 未结 7 720
你的背包
你的背包 2021-01-30 10:49

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

7条回答
  •  再見小時候
    2021-01-30 11:27

    Clojure fns are Runnable so it's common to use them in exactly the way you posted, yes.

    user=> (dotimes [i 10] (.start (Thread. (fn [] (println i)))))
    0                                                             
    1                                                             
    2                                                             
    4                                                             
    5                                                             
    3                                                             
    6                                                             
    7                                                             
    8                                                             
    9                                                             
    nil
    

    Another option is to use agents, in which case you would send or send-off and it'll use a Thread from a pool.

    user=> (def a (agent 0))
    #'user/a
    user=> (dotimes [_ 10] (send a inc))
    nil
    ;; ...later...
    user=> @a
    10
    

    Yet another option would be pcalls and pmap. There's also future. They are all documented in the Clojure API.

提交回复
热议问题