pcall 并发执行多个无参方法
Last active
April 11, 2018 05:30
-
-
Save BadUncleX/1f04d6741d2e15ace6c5f37686ebb7fb to your computer and use it in GitHub Desktop.
pcall 并发执行多个无参方法
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
;; | |
;; pcall的底层是通过pmap实现的 | |
;; | |
(defn pcalls | |
"Executes the no-arg fns in parallel, returning a lazy sequence of | |
their values" | |
{:added "1.0" | |
:static true} | |
[& fns] (pmap #(%) fns)) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
;; | |
;; pcall execute bigtask | |
;; | |
(ns alexcoding.bf.pcalldemo) | |
(defn bigtask [name] | |
(Thread/sleep 5000) | |
name | |
) | |
(comment | |
(pcalls #(bigtask "alex") #(bigtask "kate"))) | |
;; from stackeroverflow. | |
(defn sleeper [s thing] | |
(Thread/sleep (* 1000 s)) | |
thing) | |
(def actions [#(sleeper 2 :1st) #(sleeper 3 :2nd) #(keyword "3rd")]) | |
(comment | |
(apply pcalls actions)) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
;; | |
;; 来自Dennis http://blog.fnil.net/blog/964a2d5c851b7e5fd65b630a7ef96966/ | |
;; | |
;; 更多使用场景: 在用户首页登陆后的各种统计信息, 尽量用并发去DB查询, 避免串行查询。 | |
;; 比如: 用户代办信息; 站内信息; | |
;; | |
(defn add-app-info | |
"添加应用统计信息。" | |
[app] | |
(assoc app | |
:yesterday_reqs (count-reqs app 7) | |
:monthly_reqs (count-reqs app 30) | |
:total_users (count-users app))) | |
(defn get-client-apps | |
"获取用户的应用列表" | |
[client_id] | |
(->> client_id | |
(db/find-apps-by-client-id) | |
(map add-app-info))) | |
;; 改造获取用户的应用列表 | |
;; 将add-app-info的串行执行改为并行执行 | |
(defn get-client-apps | |
"获取用户的应用列表" | |
[client_id] | |
(->> client_id | |
(db/find-apps-by-client-id) | |
(pmap add-app-info))) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment