I am trying to create producer-consumer message queue system in Golang using buffered channel. Here is my implementation.
package main
import "fmt"
type MessageQueue struct {
storage chan int
count int
}
var done = make(chan bool)
func NewMessageQueue(count int) *MessageQueue {
ret := &MessageQueue{
count: count,
storage: make(chan int, count),
}
return ret
}
func (m *MessageQueue) Produce() {
for i := 0; i < m.count; i++ {
m.storage <- i + 1
}
done <- true
}
func (m *MessageQueue) Consume(f func(int) int) {
for each := range m.storage {
fmt.Printf("%d ", f(each))
}
}
func main() {
op1 := func(a int) int {
return a * a
}
msq := NewMessageQueue(10)
go msq.Produce()
go msq.Consume(op1)
<-done
}
But unfortunately, I am not able to get the output when I run go run main.go however to check if there is any race condition or not, when I try go run -race main.go, I do get the output. I am unable to understand why it is happening. Can anyone help me here?