【发布时间】:2014-09-24 12:02:24
【问题描述】:
我有一个队列,我想执行以下操作:
弹出第一个元素
如果元素是偶数,推元素+1
这应该一直持续到队列为空;此外,我想同时使用多个 goroutine。
我可以为单个 goroutine 做,但是一旦我添加了一段时间,一切都会出错,因为似乎创建了太多的 goroutine。即使放置else {return} 也无法解决问题。附带问题:为什么不呢?我得到错误:
syntax error: unexpected semicolon or newline before else
syntax error: unexpected }
var list = []int{0, 1, 2, 3}
var mutex = &sync.Mutex{}
func pop(out chan int) {
mutex.Lock()
element := list[0]
fmt.Println("element is ", element)
list = list[1:]
mutex.Unlock()
out <- element
}
func push(in chan int) {
for element := range in {
if element%2 == 0 {
mutex.Lock()
list = append(list, element+1)
fmt.Println("New list is ", list)
mutex.Unlock()
}
}
}
func main() {
out := make(chan int)
fmt.Println("MAIN")
// for len(list) != 0 {
go pop(out)
go push(out)
//}
time.Sleep(2)
}
【问题讨论】:
-
附加问题的答案:您忘记了
return后面的分号,else必须与前面的}在同一行。 -
不需要分号,但正如@tomwilde 所说,
else必须在 } 之后,在同一行中。
标签: concurrency go queue goroutine