在clojure中操纵包含ref集合的原子

时间:2018-05-12 01:24:34

标签: clojure refs

我有一个应用程序应该在指定的预算范围内为客户预订航班。因此,我有客户数据和可用的航班数据。然后我按照以下方式在Clojure中开发解决方案。

首先,我创建了一个航班原子:

(def flights
   (atom []))
然后我创建了一个函数来初始化到包含refs集合的原子的飞行。在这里,我通过了这篇文章中包含的航班数据。

(defn initialize-flights [initial-flights]
   (reset! flights (map ref initial-flights)))

然后,我通过流程客户功能处理客户,如下所示。而这正是令人困惑的地方。

(defn process-customers [customers]

(doseq [customer1 (partitionCustomerInput N-THREADS customers)]


  (doseq [customer2  customer1]

    (swap! flights
      (fn [flights_collection]
        (if-let [updated-flight (process-customer flights_collection customer2)]

          (assoc flights (:id updated-flight) updated-flight)
          flights_collection)))))


  (reset! finished-processing? true))

内部流程 - 客户我将航班集合传递给流程客户(通知流程 - 客户是流程客户的辅助功能,它们不是同一个功能)。此时的航班收集是航班参考过程的集合 - 客户应该在列表中搜索,并且如果客户有资格在其中进行航班,则它使用书籍功能来编辑航班。我应该如何将航班集合传递给流程客户?事实上,流程客户不会搜索航班参考号,也不会改变航班参考号码?

以下是process-customer函数,后跟辅助函数。

(defn- process-customer [flights customer]
  "Try to book a flight from `flights` for `customer`, returning the updated
  flight if found, or nil if no suitable flight was found."
  (if-let [{:keys [flight price]} (find-flight flights customer)]
    (let [updated-flight (book flight price (:seats customer))]
      (log "Customer" (:id customer) "booked" (:seats customer)
        "seats on flight" (:id updated-flight) "at $" price " (< budget of $"
        (:budget customer) ").")
      updated-flight)
    (do
      (log "Customer" (:id customer) "did not find a flight.")
      nil)))


(defn filter-pricing-with-n-seats [pricing seats]
  "Get `pricing` for which there are at least `seats` empty seats available."
  (filter #(>= (second %) seats) pricing))

(defn lowest-available-price [flight seats]
  "Returns the lowest price in `flight` for which at least `seats` empty seats
  are available, or nil if none found."
  (-> (:pricing flight)                 ; [[price available taken]]
    (filter-pricing-with-n-seats seats)
    (sort-pricing)
    (first)                             ; [price available taken]
    (first)))                           ; price

(defn- find-flight [flights customer]
  "Find a flight in `flights` that is on the route and within the budget of
  `customer`. If a flight was found, returns {:flight flight :price price},
  else returns nil."
  (let [{:keys [_id from to seats budget]}
          customer
        flights-and-prices
          ; flights that are on the route and within budget, and their price
          (for [f flights
                :when (and (= (:from f) from) (= (:to f) to))
                :let [lowest-price (lowest-available-price f seats)]
                :when (and (some? lowest-price) (<= lowest-price budget))]
            {:flight f :price lowest-price})
        cheapest-flight-and-price
          (first (sort-by :price flights-and-prices))]
    cheapest-flight-and-price))

(defn- book [flight price seats]
  "Updates `flight` to book `seats` at `price`."
  (update flight :pricing
    (fn [pricing]
      (for [[p a t] pricing]
        (if (= p price)
          [p (- a seats) (+ t seats)]
          [p a t])))))



(def finished-processing?
  "Set to true once all customers have been processed, so that sales process
  can end."
  (atom false))

(defn partitionCustomerInput 
  [threads customers]
  (let [partitions (partition-all 
     (Math/ceil (/ (count customers) threads))  customers)]
        partitions))

以下是主要功能。它初始化航班并启动客户处理

 (defn main []
      (initialize-flights input/flights)
       (let [f1 (future (time (process-customers input/customers)))


        @f1

        )

      (println "Flights:")
      (print-flights (map deref @flights)))
    (main)
    (shutdown-agents)

以下是客户和航班集合。

(def flights
      [{:id 0
        :from "BRU" :to "ATL"
        :carrier "Delta"
        :pricing [[600 150 0] ; price; # seats available at that price; # seats taken at that price
                  [650  50 0]
                  [700  50 0]
                  [800  50 0]]}
       {:id 1
        :from "BRU" :to "LON"
        :carrier "Brussels Airlines"
        :pricing [[300 150 0]
                  [350  50 0]
                  [370  20 0]
                  [380  30 0]]}
       {:id 2
        :from "BRU" :to "LON"
        :carrier "Brussels Airlines"
        :pricing [[250 100 0]
                  [300  50 0]]}
       {:id 3
        :from "BRU" :to "MAD"
        :carrier "Brussels Airlines"
        :pricing [[200 150 0]
                  [250  50 0]
                  [300 100 0]]}
       {:id 4
        :from "BRU" :to "MAD"
        :carrier "Iberia"
        :pricing [[250 150 0]
                  [300  50 0]]}])

(def customers
  [{:id  0 :from "BRU" :to "ATL" :seats 5 :budget 700}
   {:id  1 :from "BRU" :to "ATL" :seats 5 :budget 550}
   {:id  2 :from "BRU" :to "LON" :seats 6 :budget 270}
   {:id  3 :from "BRU" :to "ATL" :seats 4 :budget 600}
   {:id  4 :from "BRU" :to "LON" :seats 3 :budget 270}
   {:id  5 :from "BRU" :to "LON" :seats 9 :budget 250}
   {:id  6 :from "BRU" :to "MAD" :seats 5 :budget 200}
   {:id  7 :from "BRU" :to "MAD" :seats 9 :budget 150}
   {:id  8 :from "BRU" :to "LON" :seats 5 :budget 250}
   {:id  9 :from "BRU" :to "ATL" :seats 4 :budget 500}
   {:id 10 :from "BRU" :to "MAD" :seats 1 :budget 180}
   {:id 11 :from "BRU" :to "LON" :seats 2 :budget 320}
   {:id 12 :from "BRU" :to "ATL" :seats 3 :budget 850}
   {:id 13 :from "BRU" :to "ATL" :seats 4 :budget 200}])

另外,请注意我想使用refs来实现此实现以更改航班,因为ref支持协调读取和写入以原子方式更改航班。我的目标是为这个应用程序制定高度并行化的解决方案,并且不能容忍冲突。

1 个答案:

答案 0 :(得分:0)

我认为你需要一个ref而不是顶级的原子。您似乎需要协调对个别航班的更改并更改为航班列表。如果一个线程正在修改某个航班而另一个线程将其从列表中删除,该怎么办?您的process-customer副作用必须全部在(dosync)内完成。

性能方面,它应该没问题,因为如果您不在交易中修改您的航班列表引用,它将不会导致其他更改它的交易重试。

另一个原因是因为你违反了swap!的一个非常重要的规则。传递给swap!的函数必须没有副作用,因为它可以由STM重试。改变参考是副作用,并可能导致难以理解的错误。

所以我会做类似

的事情
(def flights 
  (ref [(ref {:id "flight-1"}) 
        (ref {:id "flight-2"})]))

;; Run a bunch of these in their own threads...
(doseq [customer partitioned-customers]
  (dosync (process-customer customer flights)))

然后,您可以使用altercommuteensure对流程客户进行微调,以最大限度地提高并发性并最大限度地减少重试次数。

希望这会有所帮助并祝你好运!