如何在Clojure中启动一个线程? [英] How does one start a thread in Clojure?

查看:333
本文介绍了如何在Clojure中启动一个线程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经阅读了很多关于Clojure在涉及并发性方面的优势,但我没有阅读过的教程实际上解释了如何创建线程。

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 (Thread. func)), or is there another way that I've missed?

推荐答案

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

另一个选项是 pcalls pmap 。还有 future 。它们都记录在 Clojure API 中。

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

这篇关于如何在Clojure中启动一个线程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆