DAY 12
0

把他們連結起來

``````              task--add_coutdown()    task--coutdown()
consume(f) -> |    consume(g)    | -> |              |
|                  |    |              |
produce(?) <- |  x = consume(g)  | <- |  produce(n)  |
--------------------    ----------------
``````
``````function add_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
``````

``````                -> 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]
``````

``````h = @task broadcast_tasks(gs)
``````

``````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
``````

Julia語言—從入門到專案31