1、producer-consumer問題
couroutine的一個典型的例子就是producer-consumer問題。假設有這樣兩個函數,一個不停的produce一些值出來(例如從一個file中不停地讀),另一個不斷地consume這些值(例如,寫入到另一個file中)。這兩個函數的樣子應該如下:
function producer ()while true do local x = io.read() -- produce new value send(x) -- send to consumer endendfunction consumer () while true do local x = receive() -- receive from producer io.write(x, "\n") -- consume new value endend
這兩個函數都不停的在執行,那麼問題來了,怎麼來匹配send和recv呢。究竟誰先誰後呢。兩者各自有自己的主迴圈。
採用resume-yield進行解決:
function receive (prod) local status, value = coroutine.resume(prod) return valueendfunction send (x) coroutine.yield(x)endfunction producer() return coroutine.create(function () while true do local x = io.read() -- produce new value send(x) end end)end function consumer (prod) while true do local x = receive(prod) -- receive from producer io.write(x, "\n") -- consume new value endendp = producer()consumer(p)
當一個協同調用yield時並不會進入一個新的函數,取而代之的是返回一個未決的resume的調用。相似的,調用resume時也不會開始一個新的函數而是返回yield的調用。
這種性質正是我們所需要的,與使得send-receive協同工作的方式是一致的。receive喚醒生產者生產新值,send把產生的值送給消費者消費。
開始時調用消費者,當消費者需要值時他喚起生產者生產值,生產者生產值後停止直到消費者再次請求。稱這種設計為消費者驅動的設計。
2、增加過濾器對中間資料進行處理
過濾器指在生產者與消費者之間,可以對資料進行某些轉換處理。過濾器在同一時間既是生產者又是消費者,他請求生產者生產值並且轉換格式後傳給消費者,修改上面的代碼加入過濾器。
先看一下沒加filter之前的邏輯,基本就是producer去send, send to consumer, consumer去recv, recv from producer。加了filter之後呢,因為filter需要對data做一些轉換操作,因此這時的邏輯為, producer去send,send to filter,filter去recv, recv from producer, filter去send,send to consumer , consumer去recv,recv from filter 。
完整的代碼如下:
function receive (prod) local status, value = coroutine.resume(prod) return valueendfunction send (x) coroutine.yield(x)endfunction producer() return coroutine.create(function () while true do local x = io.read() -- produce new value send(x) end end)end function consumer (prod) while true do local x = receive(prod) -- receive from producerif x thenio.write(x, "\n") -- consume new valueelsebreakend endendfunction filter(prod) return coroutine.create(function () for line = 1, math.huge do local x = receive(prod) x = string.format('%5d %s', line, x)--格式化字串, -- x = string.format('%05d %s', line, x)--輸出不足5位以0進行補齊 send(x) end end)endp = producer()f = filter(p)consumer(f)
看完上面的例子,有點兒類似unix中的pipe。使用pipe,每個task得以在各自的process裡執行,而是用coroutine,每個task在各自的coroutine中執行。pipe在writer(producer)和reader(consumer)之間提供了一個buffer,因此相對的運行速度還是相當可以的。這個是pipe很重要的一個特性,因為process間通訊,代價還是有點大的。使用coroutine,不同task之間的切換成本更小,基本上也就是一個函數調用,因此,writer和reader幾乎可以說是齊頭並進了啊。