上一篇寫得太順就把這篇的頭拿去寫到上一篇的尾巴了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的意思是廣播的意思,也就是我們平行地把工作交代給很多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了呢!!