Thursday, April 9, 2009

Long term relationship function - Var object

When you pass a function to another function as parameter than the value of the function var is passed. So if you redefine the passed function - the other function still sees the old defined function and doesn't use the new function. So if you want to establish a long term relationship between the two functions - you need to pass the Var object itself and not its value.

(defn worker []
(Thread/sleep 2000)
(prn "not working"))
Try two commands on the repl:
user> worker
#<user$worker__319 user$worker__319@cbb3fa>

user> (var worker)

user> #'worker

The reader macro #'x expands to (var x). If you have the following function which calls the worker function in a thread:
(defn worker-thread [worker-fn]
(.start (Thread. #(dotimes [i 10] (worker-fn)))))
Launch the worker thread

user> (worker-thread worker)

Fix the worker function:
(defn worker []
(Thread/sleep 2000)
(prn "working"))
You will see that the thread still printing "not working" every 5 seconds.

If you had launched the worker thread as follows:

user> (worker-thread #'worker)

and now you fix the function:
(defn worker []
(Thread/sleep 2000)
(prn "really working"))
Thread will now print the new "really printing" message.

1 comment: