How does one start a thread in Clojure?

后端 未结 7 722
你的背包
你的背包 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:17

    Just to add my two cents (7 years later): Clojure functions implement the IFn interface that extends Callable as well as Runnable. Hence, you can simply pass them to classes like Thread.

    If your project might already uses core.async, I prefer using the go macro:

    (go func)
    

    This executes func in a super lightweight IOC (inversion of control) thread:

    go [...] will turn the body into a state machine. Upon reaching any blocking operation, the state machine will be 'parked' and the actual thread of control will be released. [...] When the blocking operation completes, the code will be resumed [...]

    In case func is going to do I/O or some long running task, you should use thread which is also part of core.async (check out this excellent blog post):

    (thread func)
    

    Anyway, if you want to stick to the Java interop syntax, consider using the -> (thread/arrow) macro:

    (-> (Thread. func) .start)
    

提交回复
热议问题