【发布时间】:2017-09-01 22:00:42
【问题描述】:
换句话说,事件驱动队列的流程:
- 轮询事件队列
- 如果找到事件,处理事件,然后下一个轮询周期
- 如果未找到事件,则轮询数据队列
- 如果找到数据,推送到事件队列,开始下一轮轮询事件队列
- 如果没有找到数据,退出流程
代码如下:
package main
import "fmt"
type Queue struct {
stream []string
}
// Next returns first element from stream.
// Returns false if no element is in the stream.
func (q *Queue) Next() (s string, ok bool) {
if len(q.stream) == 0 {
return s, false
}
s = q.stream[0]
q.stream = q.stream[1:]
return s, true
}
func main() {
// define queues
events := []string{"event"}
q1 := &Queue{stream: events}
data := []string{"data1", "data2", "data3"}
q2 := &Queue{stream: data}
// poll first queue
for e, ok := q1.Next(); ok; e, ok = q1.Next() {
// nothing in q1
if !ok {
fmt.Println("Nothing found in q1")
// poll second queue
d, ok := q2.Next()
if !ok {
return
}
// found d in q2 and append to q1
fmt.Printf("found in q2 %v\n", d)
q1.stream = append(q1.stream, d)
return
}
// do some stuff to e ...
fmt.Printf("found in q1 %v %v\n", e, ok)
}
}
在操场上试试https://play.golang.org/p/bgJzq2hCfl。
我得到的只是第一个队列中的元素。
found in q1 event true
代码从不轮询第二个队列并将其元素附加到第一个队列。我怎么了?
如果我尝试
// poll first queue
for e, ok := q1.Next() {
// ...
}
编译器抛出
tmp/sandbox299553905/main.go:28:25: syntax error: e, ok := q1.Next() used as value
任何提示表示赞赏。
更新:这是循环的解决方案。
// poll first queue
for e, ok := q1.Next(); true; e, ok = q1.Next() {
// nothing in q1
if !ok {
fmt.Println("Nothing found in q1")
// poll second queue
for d, ok := q2.Next(); true; d, ok = q2.Next() {
if !ok {
fmt.Println("Nothing found in q2. exit")
return
}
// found d in q2 and append to q1
fmt.Printf("found in q2: %v. append to q1\n", d)
q1.stream = append(q1.stream, d)
break
}
continue
}
// do some stuff to e ...
fmt.Printf("found in q1: %v. do stuff\n", e)
}
你可以在操场上测试它https://play.golang.org/p/qo0zoBPROe。
【问题讨论】: