# lua 协程 消费者和生产者
function send(x)
coroutine.yield(x)
end
function producer()
return coroutine.create(
function()
f = io.open("./1.txt", 'r')
io.input(f)
while true do
local x = io.read()
if x then
print("pro. 读取到值:"..x.." stop")
send(x)
else
print("read end...")
break
end
end
end)
end
function filter(pro)
return coroutine.create(
function()
for line=1, math.huge do
print("filter recv 唤醒")
local x = recv(pro)
if x then
print("filter 过滤器收到"..x.." stop")
send(x)
else
print("收不到数据了,quit")
break
end
end
end
)
end
function recv(pro)
local s, v = coroutine.resume(pro) -- 唤醒生成者
return v
end
function consumer(cf)
while true do
print("消费者 recv 唤醒")
local x = recv(cf)
if x then
print("recv..."..x)
else
print("recv end...")
break
end
end
end
pro = producer()
f = filter(pro)
consumer(f)
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
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