2012-08-07 71 views
2

正如我测试创建10K +剂,一个单独的线程用于每个新的代理,当我创建它们。 几个代理可以在一个线程中运行吗?Clojure中

我的想法是创建10K +轻量的药剂(如在二郎演员),所以它Clojure的挑战?

感谢

+1

这些是什么药该怎么办? – dimagog 2012-08-07 19:27:04

回答

9

这是不正确。代理使用线程池,该线程池是核心数+2的大小。因此,在四核机器上,即使10k +代理也只能使用6个工作线程。

随着send,那是。随着send-off新线程将开始。

+0

感谢,但看例如下一个动作功能: '(DEFN INC状态[A] (调用println一(主题/ currentThread)) (主题/睡眠5000) (调用println一个 '完成') (合并一个{:状态(INC(A:状态))}) )' 我要让剂能在5个secods发送响应,但使用线程/睡眠 - 它需要一个线程,并不允许其他代理使用线程。我需要另一种方式在一段时间后发送动作 – Alex 2012-08-07 13:54:54

3

考虑使用jucDelayQueue

下面是它如何工作的草图,

的(delayed-function是有点麻烦在这里,但它基本上构建jucDelayed的实例提交到队列。)

(import [java.util.concurrent Delayed DelayQueue TimeUnit]) 

(defn delayed-function [f] 
    (let [execute-time    (+ 5000 (System/currentTimeMillis)) 
     remaining-delay (fn [t] (.convert t 
              (- execute-time 
               (System/currentTimeMillis)) 
              TimeUnit/MILLISECONDS))] 
    (reify 
     Delayed    (getDelay [_ t] (remaining-delay t)) 
     Runnable   (run [_] (f)) 
     Comparable (compareTo [_ _] 0)))) 

;;; Use java's DelayQueue from clojure. 
;;; See http://docs.oracle.com/javase/6/docs/api/java/util/concurrent/DelayQueue.html 

(def q (DelayQueue.)) 

(defn delayed 
    "put the function f on the queue, it will only execute after the delay 
    expires" 
    [f] 
    (.offer q (delayed-function f))) 

(defn start-processing 
    "starts a thread that endlessly reads from the delay queue and 
    executes the function found in the queue" 
    [] 
    (.start 
    (Thread. 
    #(while true 
     (.run (.take q)))))) 

user> (start-processing) 
user> (delayed #(println "Hello")) 

    ; 5 seconds passes 

Hello 
+0

感谢, 假设我们有正在执行的代理,我们有一个延迟功能,发送给执行机构的动作。那么它会并行运行还是等待代理完成当前函数的执行? – Alex 2012-08-08 09:50:47

0

the at-at libraryat功能的开发是为了支持(在我看来梦幻般的)显性一个音乐合成器提供了一个非常干净的interfase用于在特定时间点运行功能

(use 'overtone.at-at) 
(def my-pool (mk-pool)) 
(after 1000 #(println "hello from the past!") my-pool)