这个设计模式常见于并发处理

在生产者和消费者之间产生一层过滤器 过滤器对生产者产生的值进行处理后交给消费者

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
--[[
function producer()
while true do
local x = io.read()
send(x)
end
end

function consumer()
while true do
local x = receive()
io.write(x,"\n")
end
end
]]--

function receive(prob)
local status,value = coroutine.resume(prob)
return value
end

function send(x)
coroutine.yield(x) --接收到数据发送的请求后,就把当前协程给挂起
end

---生产者
function producer()
return coroutine.create(function()
while true do
local x = io.read()
send(x) --生产完以后发给协程挂起,下次resume得到的就是挂起的第一个值
end
end)
end

--消费者需要值时请求,生产者生产值通知消费者

--filter类似于装饰器
--receive接收到消费者的协程
--自己创建了一个协程,然后每次调用的时候,先从协程中取一个值
--然后把这个值再送回协程挂起...???
--也就是说它实际上是用来对当前处理的这个值做处理的一个协程
--实际的调用方式就是
--消费者->filter过滤器从生产者通过send取到值->自己对这个值进行处理以后使用send进行yield return这个值
-- ->传给consumer的那个receive -> 结束一次请求
function filter(prob)
return coroutine.create(function()
local line = 1
while true do
local x = receive(prob) --get new value
x = string.format("%5d %s",line,x)
send(x)
line = line + 1
end
end)
end

function consumer(prob)
while true do
local x = receive(prob)
io.write(x,"\n")
end
end

p = producer()
f = filter(p)
consumer(f)