This question is more classical, the basic all languages multithreading will be involved, but did not expect LUA this is so complex
It took a long time to figure it out, first the logical diagram:
Start by invoking the consumer, when the consumer needs a value, to invoke the producer production value, and the producer produces the value to stop until the consumer requests again. Designed for consumer-driven design.
The picture is not very good, you can first cover filter, it is the filter to two of programs passed between the information processing. Removing the filter logic is clearer, with two threads (in fact, two collaborating programs) calling each other. Resume goes back to yield, supports nesting, and returns to the yield position at the top of the stack. Yield is non-blocking "thread synchronization." It's kind of like a pipe communication in Linux.
function receive (PROD)
print (' receive is called ') local
status,value = Coroutine.resume (prod)
return Value
end
function Send (X,prod)
print (' send is called ') return
Coroutine.yield (x)
End function producer () return
coroutine.create (function ()
print (' producer is called ') while
true
does Print ("producer run Again") Local
x = Io.read ()
Send (x)
end
-end
function filter ( PROD) return
coroutine.create (function () to line
= 1,1000 do
print ("Enter Fliter" ...). Line) Local
x = Receive (prod)
print ("Receive in filter finished")
x= String.Format ("%5d%s", line,x)
Send (X,prod)
end
function Consumer (prod)
print ("consumer is called") While
true does
print ("Consumer run Again") Local
x = Receive (prod)
print ("Retrun customer")
Io.write (x, "\ n") end end
p = producer ()
F=filter (p)
consumer (f)
Run Result:
Consumer is called
consumer run again
receive? called
enter Fliter 1
receive is called
producer be C Alled
producer Run again
Fsy
send is called
receive in filter finished
send is called
Retrun Customer
1 Fsy
consumer run again
receive is called
enter Fliter 2
receive is called
Producer run again
Gaga
send is called
receive at filter finished
send is called
Retrun Customer
2 Gaga
consumer run again
receive is called
enter Fliter 3
receive is called
Producer Run again ...
This blog from Asura Road, reproduced please specify the source: http://blog.csdn.net/fansongy/article/details/7023332