← Back to Lua Course | Chapter 7: Coroutines | Lesson 6 of 7

Producers और Consumers

दो coroutines एक छोटे pipeline की तरह आगे-पीछे data pass कर सकते हैं।

Producers और Consumers

producer-consumer pattern में एक हिस्सा data generate करता है और दूसरा इसे process करता है। Coroutines के साथ producer हर item yield करता है और एक consumer loop इसे resume करता है और जो वापस आए उसे handle करता है। एक filter बीच में एक दूसरे coroutine की तरह बैठ सकता है, जो बिना किसी threads के एक pipeline बनाता है।

Note: एक coroutine जो normally return होता है resume के true और इसकी return values return करने के साथ खत्म होता है।

उदाहरण: Producers and consumers

lua
local function producer()
  return coroutine.create(function()
    for _, w in ipairs({"alpha", "beta", "gamma"}) do
      coroutine.yield(w)
    end
  end)
end

local function consumer(p)
  local out = {}
  while true do
    local ok, item = coroutine.resume(p)
    if not item then break end
    out[#out + 1] = item:upper()
  end
  return out
end
print(table.concat(consumer(producer()), ", "))

-- Output:
-- ALPHA, BETA, GAMMA
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
आम गलतियां
  1. producer के dead होने पर रुकना भूल जाना
  2. ज़रूरी values वापस pass किए बिना resume करना
  3. यह confuse करना कि कौन-सा side producer है और कौन-सा consumer
चैप्टर सारांश
  • Producer items yield करता है
  • Consumer इन्हें पाने के लिए resume करता है
  • Filters chain हो सकते हैं
  • रुकने के लिए status या nil check करें
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.