8

I have a multithreaded application written in Clojure. There is a problem of making a text in the console display correctly when multiple threads write to STDOUT. How can I do this correctly in Clojure, so the lines won't look interlaced? I think this would involve some kind of separate IO agent, but I'm not really sure how to do that.

1 Answer 1

9

I think this would involve some kind of separate IO agent

Yes, that should work. Create an agent (def printer (agent nil)) and call it with the appropriate print statement, e.g, (send printer #(println msg)). The messages are put in a queue and are executed (asynchronously) one at a time.

For logging purposes you could also look at tools.logging which uses agents under the hood.

Sign up to request clarification or add additional context in comments.

2 Comments

This works, except I have to send to agent a print job through an another function proxy. Sending println directly to agent won't work for some reasons.
In this article on Clojure's website, it says: "Actions dispatched to an agent from another single agent or thread will occur in the order they were sent, potentially interleaved with actions dispatched to the same agent from other sources." Does this mean there still might be problems when "multiple threads write to STDOUT"?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.