changeset 84:920b50be0fe5

Add notes (and failed code) for blocking queue
author IBBoard <dev@ibboard.co.uk>
date Sun, 09 Jun 2019 12:07:10 +0100
parents eccc649d49a2
children 67e2bb3bcccd
files 6-Clojure/README.txt 6-Clojure/blockqingqueue.clj
diffstat 2 files changed, 30 insertions(+), 1 deletions(-) [+]
line wrap: on
line diff
--- a/6-Clojure/README.txt	Sat Jun 08 21:23:27 2019 +0100
+++ b/6-Clojure/README.txt	Sun Jun 09 12:07:10 2019 +0100
@@ -143,4 +143,7 @@
 
 Futures are the same as in other languages. (future <some sequence of expressions>) creates a future that returns the last value when dereferenced with @my_future and the app blocks (unlike actors, which need (await …) to block, and that's only until your changes are complete)
 
-Clojure can also call all the standard Java methods on a Java object using (.javaMethodName object), e.g. (.toUpperCase "Using Clojure")
\ No newline at end of file
+Clojure can also call all the standard Java methods on a Java object using (.javaMethodName object), e.g. (.toUpperCase "Using Clojure")
+
+Day 3 exercise says to find a queue that blocks when it is empty. The best I can find is a wrapper on java.util.concurrent.LinkedBlockingDeque (https://gist.github.com/mjg123/1305115/72434dd5da89e5a83c91facb0b7687d6b7e66836). I've tried creating one but can't get the logic right.
+It *feels* like an atom job, then an agent to do an async push, but then you're just adding an empty check and Thread/sleep to a loop. Or you use actors with (await …) rather than atoms, but await only waits for changes in your thread, which is of minimal use with a blocking queue.
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/6-Clojure/blockqingqueue.clj	Sun Jun 09 12:07:10 2019 +0100
@@ -0,0 +1,26 @@
+(defn create_blocking_queue [] (atom []))
+
+(defn add_item [queue item]
+    (swap! queue conj item))
+
+(defn pop_item [queue]
+    (future
+        (
+            (while (empty? @queue) (do
+                (Thread/sleep 1000)
+                (print ".")
+            ))
+            ;(@queue 0)
+        )
+    )
+)
+
+(def myqueue (create_blocking_queue))
+; TODO: Add something after a period of time
+(def updater (agent myqueue))
+(send updater (fn [_q item] (Thread/sleep 5000) (add_item _q item) (println "Item added")) :item)
+(println "Scheduled an item")
+(def first_item (pop_item myqueue))
+(println "Popped an item (future)")
+(println first_item)
+(println @first_item)