0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Consumer-Producer pattern in Julia

Posted at

概要

Consumer-Producer patternの詳細
https://en.wikipedia.org/wiki/Producer%E2%80%93consumer_problem

GoF以外のデザインパターンってどこが出典なんですかね。
よくわからんけどみんな知ってますよね。

実装

# Producer
function producer(c::Channel)
    for i in 0:9
        println("produce $i")
        put!(c, i)
    end
end

# Consumer
function consumer(c::Channel)
    # inでtake!しながらイテレートしてくれる。
    for i in c
       println("consume $i")
    end
end

function main()
    BUFFER_SIZE = 2
    c = Channel(BUFFER_SIZE)
    pro_task = @async producer(c)
    # bindすると、bindしたtask終了時にChannelに対してcloseを実行してくれる。
    # Channelはclose後,バッファが空になるまではtake!できる。
    bind(c, pro_task)

    con_task = @async consumer(c)
    wait(pro_task)
    wait(con_task)
end

main()

実行結果

produce 0
produce 1
produce 2
produce 3
consume 0
consume 1
consume 2
consume 3
produce 4
produce 5
produce 6
produce 7
consume 4
consume 5
consume 6
consume 7
produce 8
produce 9
consume 8
consume 9

感想

Channelがあるから楽だけど、スコープロックみたいなのがないから自分で作ると、pthreadでロック書いてたのと同じ感じになって辛いなと思った。

0
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?