SSブログ

Lua でクロージャによる超軽量並行プロセス [Lua]

半年前の話題ですが、ブックマークの整理で「クロージャによる超軽量並行プロセスの簡単実装法」 [1] が出てきたので Lua で写経してみました。

まず安直な翻訳。

function new()
  return { senders = {}, receivers = {} }
end

function send(channel, ...)
  if #channel.receivers == 0 then
    table.insert(channel.senders, {...}) -- push
  else
    local process = table.remove(channel.receivers, 1) -- shift
    process(...)
  end
end

function receive(channel, process)
  if #channel.senders == 0 then
    table.insert(channel.receivers, process) -- push
  else
    local message = table.remove(channel.senders, 1) -- shift
    process(unpack(message))
  end
end

--[[ フィボナッチサーバ

fibc = new()

function fib()
  receive(fibc, function(n, repc)
    fib()
    if n <= 1 then
      send(repc, n)
    else
      local repc1 = new()
      local repc2 = new()
      send(fibc, n-1, repc1)
      send(fibc, n-2, repc2)
      receive(repc1, function(rep1)
        receive(repc2, function(rep2)
          send(repc, rep1+rep2)
        end)
      end)
    end
  end)
end

fib()

r = new()
send(fibc, 10, r)
receive(r, function(x) print(10, x) end)

--]]

ちょっとオブジェクト指向にした。

Channel = {}
Channel.__index = Channel

function Channel:send(...)
  if #self.receivers == 0 then
    table.insert(self.senders, {...}) -- push
  else
    local process = table.remove(self.receivers, 1) -- shift
    process(...)
  end
end

function Channel:receive(process)
  if #self.senders == 0 then
    table.insert(self.receivers, process) -- push
  else
    local message = table.remove(self.senders, 1) -- shift
    process(unpack(message))
  end
end

function Channel:new()
  local o = { senders = {}, receivers = {} }
  setmetatable(o, self)
  return o
end

こういう fib 関数の end に閉じ括弧がついたりつかなかったりというのを見ると Ruby や Scala のシンタクスは上手いこと考えてあるなあと思いますね。

追記: いくつか local 付け忘れてたのを修正。よく忘れる。

他の言語による実装一覧

* Ruby

- http://jijixi.azito.com/cgi-bin/diary/index.rb?date=20070614#p02
- http://jijixi.azito.com/cgi-bin/diary/index.rb?date=20070615#p01
- http://d.hatena.ne.jp/rubyco/20070615/cur
- http://d.hatena.ne.jp/ytakamiya/20070615#1181897876

* Scheme

- http://d.hatena.ne.jp/ishikawash/20070703/1183476554

* JavaScript

- http://d.hatena.ne.jp/sukesam/20070615/1181839050

* Smalltalk

- http://d.hatena.ne.jp/sumim/20070618/p1
- http://d.hatena.ne.jp/sumim/20070618/p2
- http://d.hatena.ne.jp/sumim/20070619/p1

[1] http://itpro.nikkeibp.co.jp/article/COLUMN/20070612/274231/


nice!(0)  コメント(0)  トラックバック(0) 
共通テーマ:パソコン・インターネット

nice! 0

コメント 0

コメントを書く

お名前:
URL:
コメント:
画像認証:
下の画像に表示されている文字を入力してください。

トラックバック 0

ScalaでKnuth-Morris-P..総称的な sum ブログトップ

この広告は前回の更新から一定期間経過したブログに表示されています。更新すると自動で解除されます。