I have a queue and I would like to perform the following operations:
pop the first element
If the element is even, push element +1
This should go on until the queue is empty; furthermore I want to use multiple goroutines at the same time.
I am able to do for a single goroutine, but as soon as I add a while everything goes wrong, since it appears that too many goroutines are created. Even putting a else {return}
will not solve the problem. Side question: why not? I get the errors:
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)
}