Producer Consumer Example

This discussion follows the discussion on the Lua Website at url Pipes and Filters

    • It gives a good example of cooperating coroutines
  • Trace through the function by hand first

  • Then put it into Eclipse and try it with the debugger
    • Put breakpoints on coroutine.yield and coroutine.receive

--- producer consumer using coroutine resume/yield to synchonize --- and pass data between the producer and consumer function receive() local status, value = coroutine.resume(producer) -- starts when other function yields return value end function send(x) coroutine.yield(x) -- yields and send value to resume end producer = coroutine.create( -- create the producer that runs the anonymous function code function () while true do local x = io.read('*L') if x == nil then os.exit(true, true) end -- kills the program when true send(x) -- calls the send function which does a yield sending data end end) function consumer() while true do local x = receive() io.write("input was -- ", x, "\n") end end io.input("C:\\lua Programming\\producerFile.txt") consumer()