How to implement a producer-consumer pattern using channels and sync in Golang?

In Go, the producer-consumer pattern can be implemented using channels and synchronization mechanisms. Here's an example of how you can do it:

package main import ( "fmt" "math/rand" "sync" "time" ) func producer(n int, out chan<- int) { defer close(out) for i := 0; i < n; i++ { time.Sleep(time.Duration(rand.Intn(1000)) * time.Millisecond) // Simulate some work out <- i // Send value to channel } } func consumer(in <-chan int, wg *sync.WaitGroup) { defer wg.Done() for value := range in { fmt.Println("Received:", value) time.Sleep(time.Duration(rand.Intn(1000)) * time.Millisecond) // Simulate some work } } func main() { rand.Seed(time.Now().UnixNano()) n := 10 // Number of values to produce bufferSize := 5 out := make(chan int, bufferSize) // Channel used to send values from producer to consumer wg := &sync.WaitGroup{} // Used to wait for all consumers to finish wg.Add(1) go consumer(out, wg) producer(n, out) wg.Wait() // Wait until all consumers finish }

In this example, we have a producer function that generates n values and sends them to the out channel. The consumer function reads from the in channel and performs some work on the received values.

In the main function, we create a buffered channel out, which is used to connect the producer and consumer. We also create a WaitGroup to wait for all consumers to finish.

We start a goroutine to run the consumer function and pass it the out channel and the WaitGroup. Then, we call the producer function, which sends n values to the out channel and closes it once done.

Finally, we call wg.Wait() to wait for all consumers to finish before exiting the program.

Note: In this example, the consumer function is only run by a single goroutine. However, you can create multiple consumer goroutines by starting multiple goroutines with the consumer function.