Hello,
Here's maybe the easiest way, with locking:
(defn give-message [message]
(locking *out*
(println (format "%s: %s" (. time-format format (. (now) getTime))
message))))
Of course, locks can introduce their own problems, so maybe the next
easiest way is with the combination of agent and send-off:
(def out (agent *out*))
(defn give-message [message]
(send-off out
#(binding [*out* %]
(println (format "%s: %s" (. time-format format (. (now) getTime))
message))
%)))
Like with a core.async approach, this gives you queue-wise execution of
give-message requests. Unlike with core.async, you don't need to manage
your own consume/print thread. Personally, I wouldn't go with core.async
until I was working with multiple consumers or had the need to 'combine'
resources.
Alan
On Friday, April 11, 2014 9:35:52 AM UTC-4, Cecil Westerhof wrote:
>
> I have the following functions in my concurrent program:
> (def time-format (new java.text.SimpleDateFormat "HH:mm:ss"))
>
> (defn now []
> (new java.util.GregorianCalendar))
>
> (defn give-message [message]
> (println (format "%s: %s" (. time-format format (. (now) getTime))
> message)))
>
>
> But sometimes a new message from a different thread is displayed, before
> the current message is ready:
> 10:34:57: Different for 4194573 (9.313226e-10, 2.220304e-16)10:34:57:
> Different for 4198042 (9.313226e-10, 2.218469e-16)
>
> 10:34:57: Different for 8389473 (1.862645e-09, 2.220217e-16)
>
>
> Is there a way to make give-message atomic, so it would be displayed as:
> 10:34:57: Different for 4194573 (9.313226e-10, 2.220304e-16)
> 10:34:57: Different for 4198042 (9.313226e-10, 2.218469e-16)
> 10:34:57: Different for 8389473 (1.862645e-09, 2.220217e-16)
>
>
> I attached the complete program. Any hints to implement it better are
> appreciated.
>
> --
> Cecil Westerhof
>
--
You received this message because you are subscribed to the Google
Groups "Clojure" group.
To post to this group, send email to [email protected]
Note that posts from new members are moderated - please be patient with your
first post.
To unsubscribe from this group, send email to
[email protected]
For more options, visit this group at
http://groups.google.com/group/clojure?hl=en
---
You received this message because you are subscribed to the Google Groups
"Clojure" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
For more options, visit https://groups.google.com/d/optout.