iT邦幫忙

2017 iT 邦幫忙鐵人賽
DAY 12
0
自我挑戰組

Julia語言—從入門到專案系列 第 12

[Day 12] Asynchronous programming--連結起來

上一篇寫得太順就把這篇的頭拿去寫到上一篇的尾巴了XD
我們繼續!

把他們連結起來

我們試著把task跟task之間串接起來:

              task--add_coutdown()    task--coutdown()
consume(f) -> |    consume(g)    | -> |              |
              |                  |    |              |
produce(?) <- |  x = consume(g)  | <- |  produce(n)  |
              --------------------    ----------------
function add_countdown(n)
    g = @task countdown(n)
    next = produce()  # 初始化
    while true
        x = consume(g)  # 先呼叫f取得值
        y = x + next  # 做點計算
        println("coutdown: ", x, ", produce: ", y)
        next = produce(y)  # produce y並且等待下個值
    end
end
f = @task add_countdown(10)
println(consume(f))
()
println(consume(f, 10))
count down from 10
coutdown: 10, produce: 20
20
println(consume(f, 10))
coutdown: 9, produce: 19
19
println(consume(f, 50))
coutdown: 8, produce: 58
58

Broadcast

Broadcast的意思是廣播的意思,也就是我們平行地把工作交代給很多Tasks完成,像下面這個樣子

                -> t
broadcast_tasks -> t
                -> t

那要怎麼做到呢?

function broadcast_tasks(targets)
    produce()
    while true
        results = []
        for t in targets
            append!(results, consume(t))
        end
        produce(results)
    end
end
gs = [@task countdown(i) for i in 5:10]

我先是宣告了一大推平行的Task

h = @task broadcast_tasks(gs)

然後再用一個Task將他們都接上這個Task

consume(h)
()

就開始試跑囉~~~

consume(h)
count down from 5
count down from 6
count down from 7
count down from 8
count down from 9
count down from 10
6-element Array{Any,1}:
  5
  6
  7
  8
  9
 10
consume(h)
6-element Array{Any,1}:
 4
 5
 6
 7
 8
 9

如此一來就可以一次控制很多task了呢!!


上一篇
[Day 11] Asynchronous programming--Task
下一篇
[Day 13] 前哨站--functional patterns
系列文
Julia語言—從入門到專案31

尚未有邦友留言

立即登入留言