Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clojure idiomatic for synching between threads

Tags:

clojure

The scenario I try to resolve is a s follows, I have a testing program that makes a web to a web endpoint on a system.

This test program has a jetty web server running on which it expects a callback from the external system that completes a successful test cycle. In case that the callback is not received during an specific time range (timeout), the test fails.

To achieve this, I want the test runner to wait on an "event" that the jetty handler will set upon callback.

I thought about using java's CyclicBarrier but I wonder if there is an idiomatic way in clojure to solve this.

Thanks

like image 483
reshefm Avatar asked Feb 04 '13 17:02

reshefm


2 Answers

You can use promise you asked about recently :) Something like this:

(def completion (promise))

; In test runner.
; Wait 5 seconds then fail.
(let [result (deref completion 5000 :fail)]
   (if (= result :success) 
     (println "Great!") 
     (println "Failed :(")))

; In jetty on callback
(deliver completion :success)
like image 95
Mikita Belahlazau Avatar answered Nov 02 '22 08:11

Mikita Belahlazau


In straight Clojure, using an agent that tracks outstanding callbacks would make sense, though in practice I would recommend using Aleph, which is a library for asynchronous web programming that makes even driven handlers rather easy. It produces ring handlers, which sounds like it would fit nicely with your existing code.

like image 38
Arthur Ulfeldt Avatar answered Nov 02 '22 08:11

Arthur Ulfeldt